【问题标题】:Generic Entity Framework mapping通用实体框架映射
【发布时间】:2017-01-19 18:16:04
【问题描述】:

刚开始我是 Expression 和 Func 的新手。

我试图避免在我的 EF 映射类中出现重复代码,但我遇到了错误的数据库。

以下面的地图类为例:

public class EntityMap : EntityTypeConfiguration<Entity>
{
    public EntityMap()
    {
        Property(x => x.PropertyA.Property);
        Property(x => x.PropertyB.Property);
    }
}

其中PropertyAPropertyB 是同一类型,并且具有许多属性 是否可以用一个简单的方法来重构它,在参数中传递 x =&gt; x.PropertyAPropertyB 并执行类似 Property(x =&gt; x. methodParemeter Property); 的操作?如何 ? 该方法可能是这样的:

private void SubMap(Expression<Func<Entity, SubEntity>> propertyExpression, string prefix)
{
    Property(x => x.propertyExpression.Property)
            .HasColumnName(string.Format("{0}{1}", prefix,"columnName"));
}

【问题讨论】:

  • 在什么方面会有所改进?
  • 我不明白你想自动将classA属性映射到class B的问题
  • 所以.Property 您的意思是例如.MaxLength(50),并且您希望在多个属性上使用更密集的语法来调用它?所以你想要{ f =&gt; f.PropertyA, f =&gt; f.PropertyB}.ForEach(p =&gt; p.MaxLength(50))这样的东西?
  • 我的建议.... 抛弃 EF 并获得 Dapper github.com/StackExchange/dapper-dot-net
  • @nurdyguy,我不能,而且 EF 也不是我的首选。

标签: c# .net entity-framework reflection lambda


【解决方案1】:

您可以使用基类和接口。

模型

public interface IEntity
{
    string PropertyA { get; set; }
    string PropertyB { get; set; }
}

public class EntityA : IEntity {
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
}

public class EntityB : IEntity
{
    public string PropertyA { get; set; }
    public string PropertyB { get; set; }
}

基类

public abstract class IEntityMap<T> : EntityTypeConfiguration<T> where T : class, IEntity
{
    protected IEntityMap()
    {
        this.Property(x => x.PropertyA);
        this.Property(x => x.PropertyB);
    }
}

映射器实现

使用您的DbContext 类型注册这些。

public class EntityAMap : IEntityMap<EntityA>
{
    public EntityAMap() : base()
    {
    }
}

public class EntityBMap : IEntityMap<EntityB>
{
    public EntityBMap() : base()
    {
    }
}

【讨论】:

    猜你喜欢
    • 2010-10-09
    • 1970-01-01
    • 2017-02-11
    • 2011-03-09
    • 2014-04-01
    • 2016-08-23
    • 2011-05-06
    • 2011-08-30
    • 2019-03-27
    相关资源
    最近更新 更多