拥有实体收藏的用法

时间:2018-12-17 20:20:29

标签: ef-core-2.2

当我运行以下代码时,出现一个异常,提示“实体类型'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");
});

0 个答案:

没有答案