I am still new to ASP.NET MVC 4 and the Entity Framework. But I started contributing to an application using both frameworks and I got this (probably auto-generated) almighty ObjectContext
implementation called ModelContainer
. It cannot easily be mocked in a testing environment and it has a lot of methods and properties (so putting an interface etc. in front of it might not be the best idea).
For instance, it has a lot of these properties:
public ObjectSet<Company> Companies { \\ ... }
My idea now was to create a simple interface like this:
public interface IDB
{
IQueryable<T> GetQueryableObjects<T>();
}
And create an adapter for the monstrosity:
public class ModelContainerDB : IDB
{
private readonly ModelContainer _db;
private static readonly Type _dbType = typeof(ModelContainer);
public ModelContainerDB(ModelContainer db)
{
_db = db;
}
public IQueryable<T> GetQueryableObjects<T>()
{
var objectType = typeof (T);
var queryableName = GetPropertyName(objectType.Name);
var propertyInfo = _dbType.GetProperty(queryableName, BindingFlags.Public | BindingFlags.Instance);
return (IQueryable<T>) propertyInfo.GetValue(_db, new object[0]);
}
private string GetPropertyName(string objectName)
{
if (objectName.EndsWith("y"))
return objectName.Remove(objectName.Length - 1) + "ies";
return objectName + "s";
}
}
I know that reflection is slow but it is kind of nice in this scenario. So my questions are:
ObjectContext
implementation are there? You could create a generic method which uses CreateObjectSet<T>
:
public IQueryable<T> GetQueryableObjects<T>()
{
return _db.CreateObjectSet<T>();
}
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.