C# 有没有一种方法可以对在运行时使用codeDOM生成的实体调用通用存储库方法?

C# 有没有一种方法可以对在运行时使用codeDOM生成的实体调用通用存储库方法?,c#,entity-framework,generics,reflection,codedom,C#,Entity Framework,Generics,Reflection,Codedom,我使用codeDOM在运行时生成实体类。我还有一个通用存储库来处理各种DB功能。以下是我的通用存储库中的Insert方法示例: public void Insert<TEntity>(TEntity entity) where TEntity : class, IBusinessEntity { if (entity == null) { throw new ArgumentNullException("entity"); } TEn

我使用codeDOM在运行时生成实体类。我还有一个通用存储库来处理各种DB功能。以下是我的通用存储库中的Insert方法示例:

public void Insert<TEntity>(TEntity entity) where TEntity : class, IBusinessEntity
{
    if (entity == null)
    {
        throw new ArgumentNullException("entity");
    }

    TEntity existing = Existing(entity);
    if (existing == null)
    {
        _context.Set<TEntity>().Add(entity);
        this._context.SaveChanges();
    }
}
但是CodeDOM创建的Thing实体不是硬编码的类,所以我必须使用type对象而不是type Thing。这是一个问题,因为我使用的是通用存储库。假设我想将这个实体插入数据库。我想打电话:

myRepository.Insert<Thing>(newThing);
myRepository.Insert(newThing);
然而,这个东西只是在运行时由CodeDOM创建的,所以它不是一个类,这意味着它不能进入。您可能已经注意到,在我上面的插入方法中,tenty也是一个IBusinessEntity。如果我尝试

myRepository.Insert<IBusinessEntity>(newThing);
myRepository.Insert(newThing);
我得到一个错误:

参数类型“object”不可分配给参数类型“Models.IBusinessEntity”

如果我尝试在没有任何东西的情况下,比如:

myRepository.Insert(newThing)

我得到一个错误:

类型“object”必须可转换为“Models.IBusinessEntity”,才能将其用作泛型方法“void Insert(tenty)”中的参数“tenty”


有人知道我如何将这个codeDOM生成的实体与通用存储库进行协调吗?反思能帮上忙吗?如果反射能以某种方式给我一类东西,并将其传递到系统中,那就太好了。另外,我应该注意,我用CodeDOM创建的所有实体都扩展了IBusinessEntity。

我认为很难让它工作,因为DbContext中包含的数据库集被EF用来创建映射。你认为如何创造它们

无论如何,使用EF不需要类型,通常可以使用GetType。 在您的方法中(现有(.)缺失,但我认为类似),您可以使用

public void Insert(object entity)
{
    if (entity == null)
        throw new ArgumentNullException("entity");

    if (!(entity is IBusinessEntity))
        throw new ArgumentInvalidException("entity is not an IBusinessEntity");

    object existing = Existing(entity);
    if (existing == null)
    {
        _context.Set(entity.GetType()).Add(entity);
        this._context.SaveChanges();
    }
}


使用Set或Set(.)我确信EF将搜索从DbContext中包含的dbset开始创建的映射。我记不起确切的异常,但我在不同的时间(当我使用DbContext.Set(myEntityType)时)播种了它。

生成的类型实现了接口吗?即使有,我也不认为您可以使用“DbSet”,因为EF在具体化实体时不知道要实例化什么对象。我也不清楚,如果模型必须匹配数据库,为什么要动态生成类型……我必须动态生成类型,因为我们允许用户创建自己的实体。因此,我们从sql表中提取有关用户希望其实体外观的数据,然后使用codeDOM创建它。我不知道如何在数据库中存储这个对象。是的,我想你是对的。我想我不能使用通用存储库,所以我必须在我的上下文类中硬编码所有的数据库集。然后在我的方法中,我可以检查实体的类型。谢谢
myRepository.Insert<IBusinessEntity>(newThing);
public void Insert(object entity)
{
    if (entity == null)
        throw new ArgumentNullException("entity");

    if (!(entity is IBusinessEntity))
        throw new ArgumentInvalidException("entity is not an IBusinessEntity");

    object existing = Existing(entity);
    if (existing == null)
    {
        _context.Set(entity.GetType()).Add(entity);
        this._context.SaveChanges();
    }