[英]Approaches to wrapping ObjectContext implementation
I am still new to ASP.NET MVC 4 and the Entity Framework. 我还是ASP.NET MVC 4和实体框架的新手。 But I started contributing to an application using both frameworks and I got this (probably auto-generated) almighty
ObjectContext
implementation called ModelContainer
. 但是我开始使用这两种框架为应用程序做贡献,并且得到了这个(可能是自动生成的)全能的
ObjectContext
实现,称为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? ObjectContext
实现的问题? You could create a generic method which uses CreateObjectSet<T>
: 您可以创建一个使用
CreateObjectSet<T>
的通用方法:
public IQueryable<T> GetQueryableObjects<T>()
{
return _db.CreateObjectSet<T>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.