开发者

Self referencing foreign key - GUID - Entity framework 4 insert problems

开发者 https://www.devze.com 2023-01-10 11:39 出处:网络
I have successfully used EF4 to insert rows automatically with a server generated GUID: http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/

I have successfully used EF4 to insert rows automatically with a server generated GUID:

http://leedumond.com/blog/using-a-guid-as-an-entitykey-in-entity-framework-4/

Now how does one perform this task if there exists a RowID (guid) and ParentRowID (guid) with a primary-foreign key constraint between the two? What would I set .ParentRowID to?

            NewCut = New Row With
            {
                .ParentRowID = .RowID
            }

SaveChanges throws a fit every time.

The fact that the primary key is a GUID is in fact irrelevant because I attempted the same test using a st开发者_如何学运维andard autogenerated integer without success.


The solution is as simple as the one you have posted.
Just create both parent and child entities in code, do not set Entity Key and not forget to set StoreGeneratedPattern for all server-generated Guid columns.
Then perform either MasterEntityInstance.Children.Add(ChildEntityInstance), or ChildEntityInstance.MasterEntity = MasTerEntityInstance and call SaveChanges.
After the SaveChanges call both guid properties will be populated with the correct Guid values, and ChildEntity.MasterEntity Entity Key will be populated with the necessary MasterEntity Entity Key value.

0

精彩评论

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

关注公众号