简体   繁体   中英

EF4 code first many to many relationship to external entity

Problem

I've got two classes:

  • OfficeProfile: exists within my EF model
  • BusinessUnit: comes from an external source, eg a web service

There is a many to many relationship between office profiles and business units, which I'd like to represent in a link table OfficeProfilesBusinessUnits . I don't want to end up with a BusinessUnits table however that contains a list of business units as these are stored in an external domain outside of my control.

Is it possible to achieve this?

public class OfficeProfile
{
    public OfficeProfile()
    {
        ContactNumbers = new HashSet<ContactNumber>();
        BusinessUnits = new HashSet<BusinessUnit>();
    }

    public int OfficeProfileId { get; set; }
    public Address Address { get; set; }
    public ICollection<ContactNumber> ContactNumbers { get; private set; }
    public ICollection<BusinessUnit> BusinessUnits { get; private set; }
}

public class BusinessUnit
{
    public BusinessUnit(string code, string name, BusinessUnit parent)
    {
        Code = code;
        Name = name;
        Parent = parent;
    }

    public string Code { get; set; }
    public string Name { get; set; }
    public BusinessUnit Parent { get; set; }
}

What I've tried

I've tried ignoring the BusinessUnit entity, however that omits the link table.

I've tried ignoring the BusinessUnit entity whilst mapping the many-to-many relationship, however that throws an InvalidOperationException stating

The navigation property 'BusinessUnits' is not a declared property on type 'OfficeProfile'. Verify that it has not been explicitly excluded from the model and that it is a valid navigation property

.

You could add an extra entity which would only have an ID and a link to the BusinessUnit. In your Entity Model you would then ignore the BusinessUnit but add the link entity so you get the many to many relation link table.

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