当我运行下面的代码时,我得到一个异常说“实体类型'ElementWeight'需要定义一个主键”。如果我想将 ElementWeight 视为值类型,为什么需要键?
var context = new DataContext(options);
context.Weightings.Add(new ImportWeighting { Name="temp", Weights = new List<ElementWeight>
{ new ElementWeight { Mag_dB = 1.0, Phase_deg = 10.0 },
new ElementWeight { Mag_dB = 2.0, Phase_deg = 20.0 }
} });
在 OnModelCreating 我执行以下操作
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<ImportWeighting>().OwnsMany(c => c.Weights);
}
这是课程
public class ImportWeighting
{
public int Id { get; set; }
public string Name { get; set; }
public List<ElementWeight> Weights { get; set; }
}
public class ElementWeight
{
public double Mag_dB { get; set; }
public double Phase_deg { get; set; }
}
如果我按照文档显示添加一个键,那么我会收到一个错误,即项目已经存在
modelBuilder.Entity<Distributor>().OwnsMany(p => p.ShippingCenters, a =>
{
a.HasForeignKey("DistributorId");
a.Property<int>("Id");
a.HasKey("DistributorId", "Id");
});