在 Entity Framework 核心中使用 [ComplexType]

Using [ComplexType] in Entity Framework Core

我在 EF Core 数据模型中使用我自己的 class 属性。

public class Currency
{
    public string Code { get; set; }
    public string Symbol { get; set; }
    public string Format { get; set; }
}

[ComplexType]
public class Money
{
    public int? CurrencyID { get; set; }
    public virtual Currency Currency { get; set; }
    public double? Amount { get; set; }
}

public class Rate
{
    public int ID { get; set; }
    public Money Price = new Money();
}

我的问题是,当我尝试创建迁移时,EF Core 报错。

Microsoft.Data.Entity.Metadata.ModelItemNotFoundException: The entity type 'RentABike.Models.Money' requires a key to be defined.

如果我声明一个密钥,则会为 "Money" 创建一个单独的 table,这不是我想要的。

有没有办法在 EF Core 中使用 ComplexType 并将其全部放入一个 table?

对复杂类型的支持目前处于积压状态 https://github.com/aspnet/EntityFramework/issues/246

Diego Vega announced Owned Entities and Table Splitting,这应该是一种不同的方法,是复杂类型的替代方法。

无法分享我的个人印象,因为我没有亲自检查过,但是 Julie Lerman, seems to have been satisfied...

你可以把[NotMapped]放在

上面
public class Rate
{
    public int ID { get; set; }
    [NotMapped]
    public Money Price = new Money();
}

像这样。

作为基于您上述评论之一的更新,您现在使用 OwnsOne 语法,在 DbContext 的 OnModelCreating 函数中使用 Fluent API。

[ComplexType]
public class Money
{
    public double? Amount { get; set; }
}

public class Rate
{
    [Key]
    public long Id { get; set; }

    public Money Price { get; set; }
}

public MyDbContext : DbContext
{
     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         modelBuilder.Entity<Rate>(entity =>
         {
             entity.OwnsOne(e => e.Currency);
         });
     }
}

我不确定它是否使用了 ComplexTypeAttribute。但是当我通过 Add-Migration 生成我的迁移时,它以这种方式为旧的 ComplexType 文档生成了预期的结果(即 table 命名为 Rate 具有列 Price_Amount)。

使用:

modelBuilder.Owned<T>: 

示例:

public MyDbContext : DbContext
{
     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         modelBuilder.Owned<Rate>();
     }
}