简体   繁体   中英

Foreign key problem with nested linq to sql insert

I have an interesting problem, i'm trying to insert nested data using l2s, all is ok if i don't try to insert an entity with fk also to root parent, sample schema:

All id's are pk identity

Testing code:

 Models.testdbDataContext db = new Models.testdbDataContext();

        List<string> data = new List<string>();

        data.Add("kkkk1");
        data.Add("kkkk2");
        data.Add("kkkk3");
        data.Add("kkkk4");
        data.Add("kkkk5");

        foreach (var item in data)
        {
            nested1 n1 = new nested1();
            n1.name1 = "test1";

            db.nested1.InsertOnSubmit(n1);

            foreach (var item2 in data)
            {
                nested2 n2 = new nested2();
                n2.name2 = "test2";

                n1.nested2.Add(n2);

                foreach (var item3 in data)
                {
                    nested3 n3 = new nested3();
                    n3.name3 = "test3";

                    n2.nested3.Add(n3);


                }
            }
        }

        db.SubmitChanges(); <-- error here (duh)

Error: "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_nested3_nested1". The conflict occurred in database "TESTDB.MDF", table "dbo.nested1", column 'id'. The statement has been terminated."

Problem is that if table nested3 has also fk to nested1 id this error happens, when nested3 has fk only to its parent nested2 id there is no problem, it seems that l2s can't get the identity from nested1 only from previous parent.

So how to overcome this?

Ok i have found the solution.

If there is another fk you need to add the current nested data also to the parent collection, this way l2s will get as many fk identity values as you need.

For this example it will be:

n1.nested3.Add(n3);

After n2.nested3.Add(n3);

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