简体   繁体   English

为T泛型创建基类

[英]Create a Base class for T generic

I have the following method: 我有以下方法:

protected override void OnModelCreating(ModelBuilder builder) {
  builder.Map<Country>();
}

And I created the following extension: 我创建了以下扩展名:

public static class CountryMapper {
  public static void Map<T>(this ModelBuilder builder) where T : Country {
    builder.Entity<T>().HasKey(x => x.Code);
  }
}

This works but I would like to have a generic base class: 这可行,但是我想有一个通用的基类:

public class CountryMapper : EntityMapper<Country> {
   // Here override the map extension ?? 
}

Basically I would like to apply Map as I am but assuring all Mappers are implemented the same way. 基本上,我想按原样应用Map,但要确保所有Mappers的实现方式都相同。

EntityMapper is a class made by you? EntityMapper是您制作的类吗? and Country can be modified? 和国家可以修改吗?

I'd add an interface like IEntity that expose a GetKey method like 我将添加一个像IEntity这样的接口,该接口公开一个GetKey方法,例如

public interface IEntity {
   object GetKey();
}

then in country (and every class you need to map), implement that interface, eg your country could looks like 然后在国家(以及您需要映射的每个班级)中实现该界面,例如您的国家可能看起来像

public class Country : IEntity{
   public string Code { get; set; }
   ...
   public object GetKey(){
      return this.Code;
   }
   ...
}

then your Map Extension could be generic and based on this interface, like 那么您的地图扩展名可能是通用的,并且基于此界面,例如

public static void Map<T>(this ModelBuilder builder) where T : IEntity {
   builder.Entity<T>().HasKey(x => x.GetKey());
}

note that i wrote it without having a chance to test, but this should point you to the right direction, there is even a little chance this is already working :) 请注意,我没有机会进行测试就写了它,但这应该为您指明了正确的方向,甚至还有一点机会已经在起作用:)

PS if you don't like to have that GetKey method to be easily accessed by anyone (or seen when using visual studio) you can implement it as an explicit interface should be PS,如果您不希望任何人都可以轻松访问该GetKey方法(或在使用Visual Studio时看到),则可以将其实现为显式接口

public class Country : IEntity{
   public string Code { get; set; }
   ...
   object IEntity.GetKey(){
      return this.Code;
   }
   ...
}

and then extension, semething like 然后扩展,像

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.

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