简体   繁体   中英

How to configure Entity Framework many-to-many with bi-directional lookup

I don't know how to properly title this question, so I did my best to come up with a descriptive title.

Basically, I have an Entity Framework entity that looks like the following ...

public class LegalDocument
{
    public int ExampleId { get; set; }
    public virtual ICollection<LegalDocument> LegalDocuments { get; set; }
}

The LegalDocument entity needs to be able to have references to other LegalDocument s. In the reverse direction, I need to be able to see what other LegalDocument s reference this LegalDocument .

So it's like several Entity Framework navigational properties, but I don't know how to specify that one of the properties is for LegalDocument s referenced within this LegalDocument , versus the other LegalDocument s that reference this one.

Any ideas?

You can maintain the relationship in code having this method in the LegalDocument class.

public void RelateDocument(LegalDocument document)
{
    LegalDocuments.Add(document);
    document.LegalDocuments.Add(this);
}

Use it to relate documents instead of using LegalDocuments.Add() directly.

This way LegalDocuments navigation property links to documents that current instance added and documents that added the current instance.

最终可以使用流畅的API的HasMany().WithMany()轻松实现。

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