C# DbContext集方法
我正在为我的测试构建一个模拟dbcontext。但是我需要从实体框架中重新实现set函数 这是我目前的代码:C# DbContext集方法,c#,entity-framework,C#,Entity Framework,我正在为我的测试构建一个模拟dbcontext。但是我需要从实体框架中重新实现set函数 这是我目前的代码: public DbSet<TEntity> Set<TEntity>() where TEntity : class, IObjectState { foreach (PropertyInfo property in GetType().GetProperties(BindingFlags.Instance | BindingFlags.N
public DbSet<TEntity> Set<TEntity>()
where TEntity : class, IObjectState
{
foreach (PropertyInfo property in GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic))
{
if (property.PropertyType == typeof(FakeDbSet<TEntity>))
return property.GetValue(this, null) as FakeDbSet<TEntity>;
}
throw new Exception("Type collection not found");
}
我的问题是我想在超类数据集中保存两个子类。
因此,我将数据集设置为如下所示:
private DbSet<BaseContact> Contacts { get; set; }
但是当我尝试使用类型Contact再次访问它时,我会得到一个异常,因为我没有首先获得超类。我该怎么做呢?我不同意您的做法,但解决您眼前问题的一个方法是,如果没有找到结果,则根据tenty的基本类型测试属性的泛型类型arg:
public DbSet<TEntity> Set<TEntity>()
where TEntity : class, IObjectState
{
var propertyInfos = GetType().GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);
foreach (PropertyInfo property in propertyInfos )
{
if (property.PropertyType == typeof(FakeDbSet<TEntity>))
return property.GetValue(this, null) as FakeDbSet<TEntity>;
}
// no joy, test for base class(es)
var baseType = typeof( TEntity ).BaseType;
while( typeof( object ) != baseType )
{
foreach( var property in propertyInfos )
{
if( property.PropertyType ==
typeof( FakeDbSet<> ).MakeGenericType( baseType )
{
var baseTypeDbSet = property.GetValue(this, null);
var entityDbSet = // you will need to convert FakeDbSet<TBaseType> to FakeDbSet<TEntity>
return entityDbSet;
}
}
baseType = baseType.BaseType;
}
throw new Exception("Type collection not found");
}
对于联系人的情况,您希望返回什么?您可以创建一个新的FakeDbSet吗?是的,这是可能的,但我不想向该数据库添加更多内容。所以就像从basecontact扩展的联系人和从basecontact扩展的电子邮件一样,我会在早上尝试。但我明白如果你说这不是一个好方法,因为我使上下文简单了很多。所以我们这样做是有原因的。