How to have a generic interface?

可紊 提交于 2019-12-13 09:49:46

问题


I want to have one interface for data access layer, and implement it for various databases (i.e. MongoDb, SQL Server, etc)

public interface IDataAccess
{
    Task InsertEntityAsync<T>(string collectionName, T entity) where T : IData;
    // the rest
}

and for a specific database:

public class MongoDbDataAccess : IDataAccess
{
    public Task InsertEntityAsync<T>(string collectionName, T entity) where T : IData
    {
        throw new NotImplementedException();
    }
}

I could make T to be instead of type StudentEntity for example, and then inside InsertEntityAsync() method convert it to a type accepted by that specific database.

But I want my method be generic, so if I pass StudentEntity, the method convert it to StudentDocument first then save it in db, if I pass UniversityEntity, the method convert it to UniversityDocument then save it, and you get the idea.

How to have a generic method to convert each data to a corresponding accepted type by the database?


回答1:


It seems that the most straightforward way to do this is to have a convert information for each type of entity, for example as a static Dictionary<TKey, TValue> inside each type:

public class StudentEntity : IData  
{  
  public static Dictionary<FieldInfo, string> ConversionInfo = new Dictionary<FieldInfo, string>
  {
    {fieldinfo1, "database column name 1"},
    {fieldinfo2, "database column name 2"},
    ...
  }
  ...
}

Where you can get fieldinfo with Type.GetField().

While doing the conversion, you should iterate through this dictionary to get all the fields you need to take into consideration.

I should warn you that digging into System.Reflection (the namespace in C#/.NET that handles meta-programming-like behaviour and analyzing types at runtime) can get really ugly really fast, so try to keep it to the minimum you need to get those fields.

Please note that this is a rough, basic description of how to use this technique, you'll need to figure out the exact details based on how it fits into your actual code.



来源:https://stackoverflow.com/questions/46993731/how-to-have-a-generic-interface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!