我正在尝试使用EF Core和ASP.NET Core 2.1建立多对多关系,并且到目前为止,我无法正常工作,而且似乎我也不理解其背后的逻辑。
所以我已经使用ModelBuilder建立了多对多关系,
builder.Entity<ComponentWare>().HasKey(cw => new { cw.ComponentId, cw.WareId });
builder.Entity<ComponentWare>()
.HasOne(x => x.Component)
.WithMany(x => x.ComponentWares)
.HasForeignKey(x => x.ComponentId);
builder.Entity<ComponentWare>()
.HasOne(x => x.Ware)
.WithMany(x => x.ComponentWares)
.HasForeignKey(x => x.WareId);
base.OnModelCreating(builder);
我的实体模型:
public class Component
{
public int ComponentId { get; set; }
public string Number { get; set; }
public string Name { get; set; }
public string MaterialType { get; set; }
public decimal? Cost { get; set; }
public float? Weight { get; set; }
public sbyte ComponentType { get; set; }
public sbyte SourceType { get; set; }
public string Comment { get; set; }
public string Author { get; set; }
public string AddedBy { get; set; }
public DateTime? ModifiedDate { get; set; }
public virtual ICollection<BookComponent> BookComponents { get; set; }
public virtual ICollection<ComponentWare> ComponentWares { get; set; }
}
public class Ware
{
public int WareId { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public decimal? Quantity { get; set; }
public string Unit { get; set; }
public decimal? Converter { get; set; }
public DateTime? Date { get; set; }
public virtual ICollection<ComponentWare> ComponentWares { get; set; }
}
还有我的联接表:
public class ComponentWare
{
public int ComponentId { get; set; }
public Component Component { get; set; }
public int WareId { get; set; }
public Ware Ware { get; set; }
public int Quantity { get; set; }
public float Length { get; set; }
public string Unit { get; set; }
}
现在,我想在Ware和Component表之间建立多对多关系,以便最终我的联接表看起来像这样。
Tables: WareId | ComponentId | ComponentWares |
1 | 1 | ComponentId | WareId |
2 | 2 | 1 | 1 |
| 1 | 1 |
| 2 | 1 |
| 2 | 1 |
这么多的组件可能有很多商品(也有重复的商品),反之亦然。
我尝试使用SQL Server资源管理器手动添加条目,但是由于
,我似乎无法添加具有相同值的多个ComponentId和WareId。HasKey(cw => new { cw.ComponentId, cw.WareId })
我已经读到上面的行对于EF Core中的多对多关系是必需的,但据我所知,它否认多对多关系的想法...
我应该从ModelBuilder中删除 ComponentId cw.WareId 键并在连接表中添加ID,还是为此提供另一种解决方案?