代码优先模型映射
本文关键字:映射 模型 代码 | 更新日期: 2023-09-27 18:09:11
我有一个类似的结构,如下所示:
public class Price
{
public decimal Amount {get; set;}
public string Currency {get; set;}
}
public class Product : BaseEntity
{
public int Id {get; set;}
public string Name {get; set;}
public Price Price {get; set;}
}
我想要一个产品表在数据库中,将价格分开到它的属性。例如,
**ProductTable**
--Id
--Name
--Amount
--Currency
然后当我从数据库中得到一个产品时,它会自动将Amount和Currency绑定到 product 的Price对象。我应该如何通过使用实体框架代码首先使这个结构?
Price属性必须是虚拟的,并且它应该工作:
public class Product
{
public int Id {get; set;}
public string Name {get; set;}
public virtual Price Price {get; set;}
}
编辑:您可以在您的DbContext
类中通过覆盖OnModelCreating
方法指定自定义列名:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>().Property(u => u.Price.Amount)
.HasColumnName("Amount");
}
@Miłosz给出的答案Wierzbicki将为Price
创建一个单独的表
但就您的情况而言,我认为您不需要另订一张桌子因此,将Price定义为Complex类型将在相同的表中与"Price"附加到数据库字段名称中相同,并且在检索或保存数据时也会自动映射名称
[ComplexType]
public class Price
{
public decimal Amount {get; set;}
public string Currency {get; set;}
}
阅读更多关于[ComplexType]