Insert using a foreign key in Entity Framework

c# entity-framework foreign-keys insert-update

Question

Sorry if there is a simple solution to this someplace. However, since a basic table has a foreign key, I am unable to enter data into it.

Task Desk

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

    which I attempt to insert as follows:

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

    But you get the following error: An association set called "FK Task Status" is adding or removing relationships. Cardinality restrictions require the addition or deletion of a matching "Task" as well.

    I need to put data into this table.

    Cheers

    ....

    I solved my problem.

    I had a flawed schema. I chose the incorrect field when I established my foreign key. I looked at SQL Profiler and discovered 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 as follows (joining on statusId rather than 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

  • 1
    4
    4/12/2010 4:44:42 PM

    Popular Answer

    You may use this straightforward method in.net framework 4.0:

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

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

    2
    8/18/2010 2:55:36 PM


    Related Questions





    Related

    Licensed under: CC-BY-SA with attribution
    Not affiliated with Stack Overflow
    Licensed under: CC-BY-SA with attribution
    Not affiliated with Stack Overflow