Clean way to deal with circular references in EF?

一笑奈何 提交于 2019-11-29 03:14:03

I'd say the answer is: "not really". The only clean way to deal with the circular reference is to look again at the design and remove it.

In this case - approaching it from a Domain Driven Design perspective - I'd say that Client is the root of your aggregate and ClientDemographic is a value object; ClientDemographics are defined by the values of their 'Other ClientDemographic fields'. You can therefore remove ClientId from ClientDemographic, and the problem is prevented instead of cured.

That said, if you're settled on this structure then unfortunately I don't think there's a neat way of handling it in EF, no.

Edit: To give Client multiple ClientDemographics as well as a CurrentClientDemographic property, you can go the other way; remove CurrentClientDemographicId from Client, and add an IsCurrent binary field to ClientDemographic. The EF then gives you a ClientDemographics collection property, and you can add the following yourself in a new, partial class:

public partial class Client
{
    public ClientDemographic CurrentDemogaphic
    {
        get { return this.ClientDemographics.First(cd => cd.IsPrimary); }
    }
}

The simple way of avoiding this error is to create your primary object first, SaveChanges and then create your dependant object before calling SaveChanges again.

In this case create the Client first, SaveChanges, then create the ClientDemographic object, add it to the collection and set it as the CurrentDemographic and then SaveChanges again.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!