我正在使用ASP.NET和Entity Framework开发一个签入系统。当您签到部门时,您可以选择在住宿期间将要使用的活动。
我有以下2个模型类:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public string Street { get; set; }
public string ZipCode { get; set; }
public string City { get; set; }
public virtual List<Activity> Activities { get; set; }
}
public class Activity
{
public int Id { get; set; }
public string Name { get; set; }
public virtual List<Department> Departments { get; set; }
}
因为这是部门与活动之间的多对多关系,EF会生成一个交叉表。
-----------------------------------
| # | Department_Id | Activity_Id |
-----------------------------------
我想在交叉表中添加一个名为displayOrder的额外列,以便每个部门都可以选择他们提供的活动以及他们想要显示的顺序。
--------------------------------------------------
| # | Department_Id | Activity_Id | DisplayOrder |
--------------------------------------------------
这是否可能与EF有关,还是有更好的方法。如果有可能,您如何保留displayOrder
属性?
答案 0 :(得分:0)
不确定您可以使EF做到这一点,但您可以使包含displayOrder属性的交叉表的局部类。
答案 1 :(得分:0)
是的,您将需要使用Department_Id,Activity_Id和DisplayOrder变量以及它们与对象示例匹配的Relations创建一个模型:
public class DepartmentActivity
{
#region Public properties
public int ActivityId{ get; set; }
public int DepartmentId{ get; set; }
public string DisplayOrder {get;set;} // this can be whatever you like and add more properties if needed
#endregion
#region Relations
public Activity Activity{ get; set; }
public Department Department { get; set; }
#endregion
}
之后,将这个DepartmentActivity类添加到您的DbSet中,以代表您的表并使其与模型构建器上的关系相符
public DbSet<DepartmentActivity> DepartmentActivities { get; set; }
modelBuilder.Entity<DepartmentActivity>().HasKey(x => new { x.ActivityId, x.DepartmentId});
modelBuilder.Entity<DepartmentActivity>()
.HasOne(x => x.Activity).WithMany(x => x.Departments );
modelBuilder.Entity<DepartmentActivity>()
.HasOne(x => x.Department).WithMany(x => x.Activities);
只需从ef运行generate migration命令,现在应该有一个具有更多可选属性的用作中间表的表