[英]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.