简体   繁体   中英

Entity Framework - Insert with foreign key

Apologies if there is clear answer for this somewhere. But I can't insert into a simple table due to it containing a foreign key.

Task Table

  • TaskId (PK)
  • Description
  • StatusId (FK)

    Into which I try to insert like so:

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

    But get an updateException error: A relationship is being added or deleted from an AssociationSet 'FK_Task_Status'. With cardinality constraints, a corresponding 'Task' must also be added or deleted.

    How can I insert into this table?

    Cheers

    ....

    Found my issue....

    My schema was wrong. When I created my foreign key I pointed it to the wrong field. Had a look in SQL profiler, saw 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]

    Which should be this (joining on 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]

    Silly me ;)

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

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

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

    Using "Entity Framework 1.0" (the version that was, until today, the most current) you have the right idea- get the Status from the database to set on the Task. Are you sure you're actually getting a Status entity with the syntax you're using above?

    Step through your code to make sure the reference on the Task entity is being set to an actual materialized Status entity.

    you can try

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

    hope this will work

    The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM