简体   繁体   中英

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.

EntityMapper is a class made by you? and Country can be modified?

I'd add an interface like IEntity that expose a GetKey method like

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

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

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.

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