我试图建立一个多使用EF Core和ASP.NET 2.1的核心一对多的关系,并为现在我无法得到这个工作,似乎我不明白它背后的逻辑无论是。
所以,我有很多的设置使用模型构建器很多这样的关系:
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; }
}
现在,我想设置一个许多人洁具和组件表之间一对多的关系,这样在结束我的连接表是这样的。
Tables: WareId | ComponentId | ComponentWares |
1 | 1 | ComponentId | WareId |
2 | 2 | 1 | 1 |
| 1 | 1 |
| 2 | 1 |
| 2 | 1 |
因此,许多组件可以有很多产品(也复制),反之亦然。
我曾尝试使用SQL Server Explorer中手动添加条目,但似乎我不能添加多个COMPONENTID和WareId有因为相同的价值观
HasKey(cw => new { cw.ComponentId, cw.WareId })
我读过,上面的线是必要的许多人在EF核心一对多的关系,但对我的理解它否定了许多想法一对多的关系...
我应该从模型构建器中删除COMPONENTID cw.WareId键,在连接表中添加标识或者是这个另一种解决方案?