To beginning I'm novice with Expression and Func.
I'm trying to avoid duplicate code in my EF mapping class, and I'm stuck with bad database.
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);
? 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.
public class EntityAMap : IEntityMap<EntityA>
{
public EntityAMap() : base()
{
}
}
public class EntityBMap : IEntityMap<EntityB>
{
public EntityBMap() : base()
{
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.