请尝试以下操作并注意Id
你班级的财产NestedProp
。 EF(Core)在每个模型中都需要一个主键,否则它将无法工作。
Models
public class Class1
{
public int Id { get; set; }
public virtual NestedProp NestedProp { get; set; } = new NestedProp();
}
public class NestedProp
{
public int Id { get; set; }
public decimal Prop1 { get; set; }
}
模型创建时
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var class1Entity = modelBuilder.Entity<Class1>();
class1Entity.HasOne(p => p.NestedProp);
var nestedPropEntity = modelBuilder.Entity<NestedProp>();
nestedPropEntity.Property(p => p.Prop1)
.HasColumnType("NUMERIC(38, 16)"); // maybe decimal instead of numeric?
}
在这里你会发现更多解释 https://www.learnentityframeworkcore.com/configuration/one-to-one-relationship-configuration。
您必须为每个模型定义配置。
我建议使用IEntityTypeConfiguration<T>
而不是配置所有内容OnModelCreating
.
您会发现有关在 EF Core 中使用 Fluent API 的精彩介绍here https://www.learnentityframeworkcore.com/configuration/fluent-api or here http://www.entityframeworktutorial.net/efcore/entity-framework-core.aspx.
EDIT:
上面的解决方案将创建两个表,因为它实现了两种自己的数据类型。不是列中所询问的复杂类型。因此我也会为这个解决方案提供建议。这种拥有的类型映射可以通过以下方式实现entity.OwnsOne(...)
方法。也可以像本文中提到的那样进行拆分MS 文档文章 https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities#mapping-owned-types-with-table-splitting。在这个article https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities#explicit-configuration您还将找到如何显式配置它。
这里是包含您的代码和 Fluent API 的示例:
Models
public class Class1
{
public int Id { get; set; }
public virtual NestedProp NestedProp { get; set; } = new NestedProp();
}
public class NestedProp
{
public decimal Prop1 { get; set; }
}
模型创建时
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var class1Entity = modelBuilder.Entity<Class1>();
class1Entity.OwnsOne(
class1 => class1.NestedProp,
nestedProp =>
{
nestedProp.Property(p => p.NestedProp)
.HasColumnType("NUMERIC(38, 16)")
.HasColumnName("NestedPropValue"); // here you could add a custom name like I did or remove it and you get a generated one
});
}