Asp.net core mvc 在实体框架核心中使用[ComplexType]
我在EF核心数据模型中使用自己类的属性Asp.net core mvc 在实体框架核心中使用[ComplexType],asp.net-core-mvc,entity-framework-core,Asp.net Core Mvc,Entity Framework Core,我在EF核心数据模型中使用自己类的属性 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 v
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”创建一个单独的表,这不是我想要的
有没有办法在EF Core中使用ComplexType并将其全部放在一个表中?对复杂类型的支持目前正在公布的待办事项中,这应该是一种不同的方法和复杂类型的替代方案
无法分享我的个人印象,因为我没有亲自检查,但是,…您可以将[NotMapped]放在上面
public class Rate
{
public int ID { get; set; }
[NotMapped]
public Money Price = new Money();
}
类似于此。作为基于上面一条评论的更新,您现在可以使用DbContext的
OnModelCreating
函数中的Fluent API使用OwnsOne
语法
[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);
});
}
}
[ComplexType]
公款
{
公共双倍?金额{get;set;}
}
公费
{
[关键]
公共长Id{get;set;}
公共货币价格{get;set;}
}
公共MyDbContext:DbContext
{
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Entity(Entity=>
{
实体.OwnsOne(e=>e.Currency);
});
}
}
实际上,我不确定它是否使用了ComplexTypeAttribute
。但当我通过Add migration生成迁移时,它按预期的方式为旧ComplexType文档生成(即名为Rate
的表中有一列Price\u Amount
)。使用:
modelBuilder.Owned<T>:
modelBuilder.Owned:
例如:
public MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Owned<Rate>();
}
}
公共MyDbContext:DbContext
{
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
modelBuilder.Owned();
}
}
这是否得到支持,还是我做错了什么?您必须使用fluentApi将对象声明为复杂对象吗?EF Core 2.0最终支持它:您必须使用一些fluent API来配置它,但注释还不受支持。@SergeyKandaurov从EF Core 2.1开始,您现在可以使用
[Owned]
属性表示拥有的类型。这不会将其置于db@SergeyKandaurov是的,因为Money类没有任何主键值,所以它不是一个实体。如果它不是实体,那么它将不会映射到db。但是你可以在外部使用它,但它的值不会存储在db中,或者你可以简单地添加[Owned]实体类本身上的属性