简体   繁体   English

通用实体框架映射

[英]Generic Entity Framework mapping

To beginning I'm novice with Expression and Func. 首先,我是Expression和Func的新手。

I'm trying to avoid duplicate code in my EF mapping class, and I'm stuck with bad database. 我正在尝试避免在EF映射类中出现重复的代码,并且卡在错误的数据库中。

Take the following example map class: 采取以下示例地图类:

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

Where PropertyA and PropertyB are same type, and with many property Is it possible to refactor this with a simple method, pass x => x.PropertyA or PropertyB in parameters and do something like Property(x => x. methodParemeter Property); 其中PropertyAPropertyB是相同类型,并且具有许多属性是否可以通过一种简单的方法对其进行重构,在参数中传递x => x.PropertyAPropertyB并执行类似于Property(x => x. methodParemeter Property); ? And how ? 如何 ? The method could be something like that: 该方法可能是这样的:

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

You could do with with a base class and an interface. 您可以使用基类和接口。

Models 楷模

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

Base class 基类

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

Mapper Implementations 映射器实现

Register these with your DbContext type. 用您的DbContext类型注册这些。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM