开发者

Attaching an object tree to object context in Entity Framework

I have an EDM with the following three types: Foo, Bar and Foob. Foob is a subclass of Foo. Foo has a collection of Bar entities. Bar has a collection of Foo entities. I want to add a new Foo object to the collection, along with it's Bar and associated Foob objects. Such that the following code would work:

Foo foo = new Foo(){Name = "Foo"};
using(var ctx = new EntityContext())
{
ctx.Foo.Attach(foo);
Bar bar = new Bar();
bar.Items.Add(new Foob(){Name="Foob1"};
bar.Items.Add(new Foob开发者_如何学C(){Name="Foob2"};
foo.Bars.Add(bar);
ctx.SaveChanges();
}

However the above code gives me the exception below:

System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.tblFoo' with unique index.


Try to check sql code that executed for this in SQL profiler. May be you forgot set autoincrement for Foob entity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜