有人可以解释为什么Entity Framework不会在连接表中创建额外的列CurVal
和NewVal
吗?它正在创建一个包含DeviceFeatureID
和UserDeviceID
的联接表。
public class DeviceFeature
{
[Display(Name = "ID")]
public int DeviceFeatureID { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<DeviceType> DeviceTypes { get; set; }
public virtual ICollection<UserDevice> UserDevices { get; set; }
}
public class UserDevice
{
public int UserDeviceID { get; set; }
public int DeviceTypeID { get; set; }
public string UserID { get; set; }
public string DeviceName { get; set;}
public virtual ICollection<DeviceFeature> DeviceFeatures { get; set; }
}
public class UserDeviceFeatureStatus
{
public int UserDeviceID { get; set; }
public int DeviceFeatureID { get; set; }
public virtual UserDevice UserDevice { get; set; }
public virtual DeviceFeature DeviceFeature { get; set; }
public string CurVal { get; set; }
public string NewVal { get; set; }
}
答案 0 :(得分:0)
您的多对多关系表由您的虚拟馆藏自动生成,而不是由您的实体生成。
您可以在DbContext中包含连接实体(但它可能会复制表,除非您删除虚拟集合),或者您可以使用Fluent API来配置关系。
要执行稍后操作,您需要将虚拟馆藏更改为ReleationShip类型并将其添加到OnModelCreating:
modelBuilder.Entity<UserDeviceFeatureStatus>()
.HasKey(t => new { t.UserDeviceID, t.DeviceFeatureID });
modelBuilder.Entity<UserDeviceFeatureStatus>()
.HasOne(pt => pt.UserDevice)
.WithMany(p => p.DeviceFeatures) // from UserDevice
.HasForeignKey(pt => pt.UserDeviceID);
modelBuilder.Entity<UserDeviceFeatureStatus>()
.HasOne(pt => pt.DeviceFeature)
.WithMany(t => t.UserDevices) //from DeviceFeature
.HasForeignKey(pt => pt.DeviceFeatureID);
在DeviceFeature中
public virtual ICollection<UserDeviceFeatureStatus> UserDevices { get; set; }
在UserDevice中
public virtual ICollection<UserDeviceFeatureStatus> DeviceFeatures { get; set; }
有关EF关系的详细信息,您可以查看文档here。
答案 1 :(得分:0)
如果您想在UserDevice
和DeviceFeature
到UserDeviceFeatureStatus
之间建立多对多关系,那么您需要将2个表格中的导航属性设置为&#34 ;加入&#34;表。我们了解到,您尝试直接从UserDevice
导航到DeviceFeature
,反之亦然。但如果您的关系表包含的其他字段不是您尝试链接的表格的主键,那么您将无法在EF中执行此操作。
你可以试试这个:
public class DeviceFeature
{
[Display(Name = "ID")]
public int DeviceFeatureID { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<DeviceType> DeviceTypes { get; set; }
public virtual ICollection<UserDeviceFeatureStatus> UserDeviceFeatureStatuses { get; set; }
}
public class UserDevice
{
public int UserDeviceID { get; set; }
public int DeviceTypeID { get; set; }
public string UserID { get; set; }
public string DeviceName { get; set;}
public virtual ICollection<UserDeviceFeatureStatus> UserDeviceFeatureStatuses { get; set; }
}
public class UserDeviceFeatureStatus
{
public int UserDeviceID { get; set; }
public int DeviceFeatureID { get; set; }
public virtual UserDevice UserDevice { get; set; }
public virtual DeviceFeature DeviceFeature { get; set; }
public string CurVal { get; set; }
public string NewVal { get; set; }
}
例如,要从UserDevice
导航到DeviceFeature
,您需要先导航到UserDeviceFeatureStatus
然后再导航到DeviceFeature
。