【问题标题】:EF Core fluent mapping to inner object propertiesEF Core 流利映射到内部对象属性
【发布时间】:2016-03-01 17:47:01
【问题描述】:

我有一个包含一些属性的类。 由于某些架构原因,我的班级中有另一个对象的实例。

简单示例

public class MyEntity {
   public MySubEntity SubEntity {get; set;}
}

为此,我创建了流畅的映射,例如:

builder.ToTable(MyEntity.CONST_TABLE_NAME);
builder.HasKey(m => m.Id);
builder.Property(m => m.Column1).IsRequired();
builder.Property(m => m.SubEntity.Column2).IsRequired();

我无法将所有 subEntity 属性集成到我的主实体中(我的 subEntity 有自己的智能)。我只想将未存储在单独表中的子实体属性映射到 myEntity 表。

最后一行抛出异常:

The expression 'm => m.SubEntity.Column2' is not a valid property expression. The expression should represent a property access: 't => t.MyProperty'.

我怎样才能进行这样的映射?

【问题讨论】:

    标签: c# entity-framework-core fluent-entity-framework


    【解决方案1】:

    EF Core 目前不支持这种类型的映射。 EF Core 1.0 RTM 将不支持它(请参阅我的 github 问题:https://github.com/aspnet/Home/issues/1330

    正如我在 github 问题中所描述的,我想出了 2 个解决方案:

    1) 从我的模型创建一个专门为 EF 设计的派生类,并简单地公开所有属性。从 Db 插入/更新和检索时,它将需要更多映射。我们不选择这个选项

    2) 创建代理属性。在我的例子中,这就像:

    public class MyEntity {
       private MySubEntity SubEntity {get; set;}
       public string SubEntityValue 
       { 
         get 
         { 
             return SubEntity.Value;
         } 
         set 
         { 
             SubEntity.Value = value; 
         }
    }
    

    这似乎是最好的解决方案(我们选择了这个)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-18
      • 1970-01-01
      • 1970-01-01
      • 2023-02-23
      • 2020-06-25
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多