Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...