Entity Framework - insert using a foreign key

Sorry if there is a clear answer for this. But I can’t insert into a simple table because it contains a foreign key.

Task table

TaskId (PK) Description StatusId (FK)

In which I am trying to insert like this:

Task t = new Task(); t.Id = 1234; t.Title = "foo"; t.Status = db.Status.ToList().First(); 

But get an updateException error: <i> A link is being added or removed from the association "FK_Task_Status". With power limitations, you must also add or remove the corresponding "Task".

How can I insert into this table?

Greetings

....

Found my problem ....

My circuit was wrong. When I created my foreign key, I pointed to the wrong field. If you look in the SQL profiler, you see this:

SELECT 1 AS [C1], [Extent1]. [Id] AS [Id], [Extent1]. [Descr] AS [Descr], [Extent2]. [Id] AS [Id1] FROM [dbo]. [Status] AS [Extent1] LEFT OUTER JOIN [dbo]. [Task] AS [Extent2] ON [Extent1]. [Id] = [Extent2]. [Id]

What should this be (joining statusId not id):

SELECT 1 AS [C1], [Extent1]. [Id] AS [Id], [Extent1]. [Descr] AS [Descr], [Extent2]. [Id] AS [Id1] FROM [dbo]. [Status] AS [Extent1] LEFT OUTER JOIN [dbo]. [Task] AS [Extent2] ON [Extent1]. [Id] = [Extent2]. [StatusId]

Stupid me;)

+4
source share
3 answers

in .net framework 4.0 u you can use this simple way:

  Task t = new Task(); t.Id = 1234; t.Title = "foo"; t.StatusId = 5678; 

link: http://blogs.msdn.com/b/adonet/archive/2009/11/06/foreign-key-relationships-in-the-entity-framework.aspx

+2
source

Using "Entity Framework 1.0" (the version that was until today, the latest), you have the right idea - get the status from the database for installation in the Task. Are you sure you are actually getting a Status object with the syntax you use above?

Go through your code to make sure that the link to the Task object is set to the real materialized State object.

0
source

you may try

  Task t = new Task(); t.Id = 1234; t.Title = "foo"; t.Status.EntityKey = new EntityKey("tblStatus","StatusId",t.StatusID); 

hope it works

0
source

Source: https://habr.com/ru/post/1306713/


All Articles