[英]Create a Base class for T generic
我有以下方法:
protected override void OnModelCreating(ModelBuilder builder) {
builder.Map<Country>();
}
我创建了以下扩展名:
public static class CountryMapper {
public static void Map<T>(this ModelBuilder builder) where T : Country {
builder.Entity<T>().HasKey(x => x.Code);
}
}
这可行,但是我想有一个通用的基类:
public class CountryMapper : EntityMapper<Country> {
// Here override the map extension ??
}
基本上,我想按原样应用Map,但要确保所有Mappers的实现方式都相同。
EntityMapper是您制作的类吗? 和国家可以修改吗?
我将添加一个像IEntity这样的接口,该接口公开一个GetKey方法,例如
public interface IEntity {
object GetKey();
}
然后在国家(以及您需要映射的每个班级)中实现该界面,例如您的国家可能看起来像
public class Country : IEntity{
public string Code { get; set; }
...
public object GetKey(){
return this.Code;
}
...
}
那么您的地图扩展名可能是通用的,并且基于此界面,例如
public static void Map<T>(this ModelBuilder builder) where T : IEntity {
builder.Entity<T>().HasKey(x => x.GetKey());
}
请注意,我没有机会进行测试就写了它,但这应该为您指明了正确的方向,甚至还有一点机会已经在起作用:)
PS,如果您不希望任何人都可以轻松访问该GetKey方法(或在使用Visual Studio时看到),则可以将其实现为显式接口
public class Country : IEntity{
public string Code { get; set; }
...
object IEntity.GetKey(){
return this.Code;
}
...
}
然后扩展,像
public static void Map<T>(this ModelBuilder builder) where T : IEntity {
builder.Entity<T>().HasKey(x => ((IEntity)x).GetKey());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.