c# - EF4 代码首先与外部实体建立多对多关系

标签 c# entity-framework entity-framework-4.1 ef-code-first ef4-code-only

问题

我有两个类:

  • OfficeProfile:存在于我的 EF 模型中
  • BusinessUnit:来自外部来源,例如网络服务

办公室资料和业务单位之间存在多对多关系,我想在链接表 OfficeProfilesBusinessUnits 中表示这种关系。我不想以 BusinessUnits 表结束,但是它包含业务单位列表,因为这些业务单位存储在我无法控制的外部域中。

这有可能实现吗?

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; }
}

我尝试过的

我试过忽略 BusinessUnit 实体,但是忽略了链接表。

我尝试在映射多对多关系时忽略 BusinessUnit 实体,但这会引发 InvalidOperationException 声明

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

.

最佳答案

您可以添加一个额外的实体,它只有一个 ID 和一个指向 BusinessUnit 的链接。在您的实体模型中,您将忽略 BusinessUnit 但添加链接实体,以便您获得多对多关系链接表。

关于c# - EF4 代码首先与外部实体建立多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8309679/

相关文章:

c# - 如何在 ASP MVC 的所有 View 中保存用户名称?

c# - Golang - DTO、实体和映射

c# - 强制 Entity Framework 6 查询使用正确的索引

asp.net-mvc-3 - DropDownList 结果未返回

c# - Entity Framework Code First 对象实例化回调

entity-framework-4.1 - Entity Framework 4.1 Database First 未向 DbContext T4 生成的类添加主键

c# - 绑定(bind)命令以从集合中删除 self

javascript - 如何在没有表单的情况下从 $.post(...) 方法传递 guid 或字符串?

c# - LINQ to SQL 多表左外连接

asp.net-mvc - 如何为启用延迟加载的 MVC 应用程序应用事务隔离级别?