我有一个非常具体的问题,我想在这里寻求帮助。 我正在将.NET Core 2.1.1与EF Core 2.1.1一起使用。我正在使用代码优先方法,目前正在为我的应用程序设计域模型。
所以我有以下要求:我有一个TrainingItem
类,其中包含有关培训的基本信息。 TrainingItem
还包含与会者列表,因此我正在使用TrainingItem
和TrainingEmployee
之间的多对多关系。问题是我要求TrainingItem
包含等待培训的员工列表,因此我想出了以下方法:
public class TrainingItem
{
// ... properties for Training
public virtual ICollection<TrainingEmployeeTrainingItem> Attendees {get;set;} = new List<TrainingEmployeeTrainingItem>();
public virtual ICollection<TrainingEmployeeTrainingItem> WaitingList {get;set;} = new List<TrainingEmployeeTrainingItem>();
}
public class TrainingEmployee
{
// ... properties for Employee
public virtual ICollection<TrainingEmployeeTrainingItem> TrainingEmployeeTrainingItems {get;set;} = new List<TrainingEmployeeTrainingItem>();
}
public class TrainingEmployeeTrainingItem
{
public int TrainingEmployeeId {get;set;}
public virtual TrainingEmployee TrainingEmployee {get;set;}
public int TrainingItemId {get;set;}
public virtual TrainingItem TrainingItem {get;set;}
}
// this is my model creating method in db context
protected override void OnModelCreating(ModelBuilder builder)
{
// many-to-many
builder.Entity<TrainingEmployeeTrainingItem>()
.HasKey(x => new { x.TrainingEmployeeId, x.TrainingItemId });
}
因此,如您所见,可以使用EF Core中当前用于映射多对多关系的解决方法来映射第一个与会者列表。
但问题是,如何映射WaitingList?
答案 0 :(得分:2)
您需要多对多的实体,因此只有TrainingEmployeeTrainingItem
不会。
尝试以下操作:
public class TrainingItem
{
// ... properties for Training
public virtual ICollection<AttendeeTrainingEmployeeTrainingItem> Attendees {get;set;} = new List<AttendeeTrainingEmployeeTrainingItem>();
public virtual ICollection<WaitingListTrainingEmployeeTrainingItem> WaitingList {get;set;} = new List<WaitingListTrainingEmployeeTrainingItem>();
}
public class TrainingEmployee
{
// ... properties for Employee
public virtual ICollection<AttendeeTrainingEmployeeTrainingItem> AttendingTrainings {get;set;} = new List<AttendeeTrainingEmployeeTrainingItem>();
public virtual ICollection<WaitingListTrainingEmployeeTrainingItem> AwaitingTrainings {get;set;} = new List<WaitingListTrainingEmployeeTrainingItem>();
}
public abstract class TrainingEmployeeTrainingItem
{
public int TrainingEmployeeId {get;set;}
public virtual TrainingEmployee TrainingEmployee {get;set;}
public int TrainingItemId {get;set;}
public virtual TrainingItem TrainingItem {get;set;}
}
public class AttendeeTrainingEmployeeTrainingItem : TrainingEmployeeTrainingItem
{
}
public class WaitingListTrainingEmployeeTrainingItem : TrainingEmployeeTrainingItem
{
}
// this is my model creating method in db context
protected override void OnModelCreating(ModelBuilder builder)
{
// many-to-many
builder.Entity<AttendeeTrainingEmployeeTrainingItem>()
.HasKey(x => new { x.TrainingEmployeeId, x.TrainingItemId });
builder.Entity<WaitingListTrainingEmployeeTrainingItem>()
.HasKey(x => new { x.TrainingEmployeeId, x.TrainingItemId });
}
答案 1 :(得分:1)
我之前answered是question(值得注意的是您的问题不是重复的,因为它是针对核心而不是老式EF的。)
You can apply InversePropertyAttribute
到您的收藏集。