在ef core 2.0中有复杂类型的列类型

时间:2018-03-22 12:08:03

标签: c# entity-framework ef-code-first ef-core-2.0

我想使用流畅的api更改属性的列类型,但我有一个错误

表达式'x => x.NestedProp.Prop1'不是有效的属性表达式。表达式应代表属性访问:'t => t.MyProperty”。

请,我不想使用DataAnnotations

这是我的代码(Classes):

public class Class1 {
     public int Id { get; set; }
     public NestedProp NestedProp { get; set; } = new NestedProp();
}

public class NestedProp {
     public decimal Prop1 { get; set; }
}

OnModelCreating:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Class1>(e =>
            {
                e.OwnsOne(t => t.NestedProp);
                e.Property(p => p.NestedProp.Prop1).HasColumnType("NUMERIC(38, 16)");
            });
}

1 个答案:

答案 0 :(得分:2)

请尝试以下操作,并注意班级Id中的NestedProp媒体资源。 EF(Core)在每个模型中都需要一个主键,否则它将无法工作。

<强>模型

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; }
}

<强> OnModelCreating

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?
}

在这里你会发现更多explanation。 您必须为每个模型定义配置。

我建议使用IEntityTypeConfiguration<T>而不是配置OnModelCreating中的所有内容。

在EF Core中使用Fluent API的一个很好的介绍,你会发现herehere

修改

上面的解决方案将创建两个表,因为它实现了两种自己的数据类型。没有问题在列上询问复杂类型。因此,我也会为这个解决方案提供建议。可以通过entity.OwnsOne(...)方法实现此拥有的类型映射。也可以像本MS doc article中提到的那样进行拆分。在此article中,您将找到如何明确配置它。

这里是您的代码和流畅API的示例:

<强>模型

public class Class1 
{
     public int Id { get; set; }

     public virtual NestedProp NestedProp { get; set; } = new NestedProp();
}

public class NestedProp
{
     public decimal Prop1 { get; set; }
}

<强> OnModelCreating

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
            });
}