簡體   English   中英

通用實體框架映射

[英]Generic Entity Framework mapping

首先,我是Expression和Func的新手。

我正在嘗試避免在EF映射類中出現重復的代碼,並且卡在錯誤的數據庫中。

采取以下示例地圖類:

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

其中PropertyAPropertyB是相同類型,並且具有許多屬性是否可以通過一種簡單的方法對其進行重構,在參數中傳遞x => x.PropertyAPropertyB並執行類似於Property(x => 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"));
}

您可以使用基類和接口。

楷模

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()
    {
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM