Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

c# - How to have a generic interface?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...