EF7巩固了多对多关系

时间:2015-12-29 13:06:27

标签: entity-framework entity-framework-core

我有以下示例代码:

public class User {
    public int ID {get;set;}
    public virtual ICollection<Task> Tasks {get;set;}
}

public class Task {
    public int ID {get;set;}
    public string Description {get;set;}
    public virtual ICollection<User> Responsible {get;set;}
    public virtual ICollection<User> Accountable {get;set;}
    public virtual ICollection<User> Consulted {get;set;}
    public virtual ICollection<User> Informed {get;set;}
}

现在我可以使用流畅的API来创建这些关系,但是这会为每个属性创建一个新表:

ResponsibleID | UserID | TaskID
-------------------------------
1             | 1      | 1

AccountableID | UserID | TaskID
-------------------------------
1             | 1      | 1

etc.

但我宁愿把它们存放在一张表中:

ResponsibilityID | UserID | TaskID | Responsibility
----------------------------------------------------
1                | 1      | 1      | Responsible
2                | 1      | 1      | Accountable
3                | 3      | 1      | Consulted
4                | 17     | 1      | Informed

多对多课程应该是这样的:

public class UserTaskResponsibility {
    public ID {get;set;}
    public User User {get;set;}
    public Task Task {get;set;}
    public UserResponsibility Responsibility{get;set;}
}

public enum UserResponsibility {
    Responsible,
    Accountable,
    Consulted,
    Informed
}

编辑: 使用此类我将属性更改为

public class User {
    public int ID {get;set;}
    public virtual ICollection<UserTaskResponsibility> Tasks {get;set;}
}

public class Task {
    public int ID {get;set;}
    public string Description {get;set;}
    public virtual ICollection<UserTaskResponsibility> Responsible {get;set;}
    public virtual ICollection<UserTaskResponsibility> Accountable {get;set;}
    public virtual ICollection<UserTaskResponsibility> Consulted {get;set;}
    public virtual ICollection<UserTaskResponsibility> Informed {get;set;}
}

表格在

中创建了结果
ResponsibilityID | UserID | TaskID | Responsibility | TaskTaskID | TaskTaskTaskID | TaskTaskTaskTaskID
------------------------------------------------------------------------------------------------------
1                | 1      | 1      | Responsible    | Null       | Null           | Null              
2                | 1      | 1      | Accountable    | Null       | Null           | Null              
3                | 3      | 1      | Consulted      | Null       | Null           | Null              
4                | 17     | 1      | Informed       | Null       | Null           | Null              

它为集合的每个引用添加了一个额外的ID列。 (负责任务,负责任务任务等)。

如何告诉这些不同的属性引用同一列?

1 个答案:

答案 0 :(得分:0)

您已经回答了问题!将UserTaskResponsibility类添加到您的datacontext作为新表,然后更改您的模型:

public class User {
    public int ID {get;set;}
    public virtual ICollection<UserTaskResponsibility> Links {get;set;}
}

public class Task {
    public int ID {get;set;}
    public string Description {get;set;}
    public virtual ICollection<UserTaskResponsibility> Links {get;set;}
}