包含实体框架的通用Find()

Mat*_*cic 4 c# generics entity-framework

我现在有一个完整的通用仓库,但我缺少一个特点,那就是使用 包括()Find()在一起.

所以现在我有:

public E FindById<E>(int id) where E : class
{
    return DataContext.Set<E>().Find(id);
}
Run Code Online (Sandbox Code Playgroud)

叫做使用

var person = PersonRepo.FindById<Person>(personId);
Run Code Online (Sandbox Code Playgroud)

我想有类似的东西:

var person = PersonRepo.FindByIdWithIncludes<Person>(personId,new[]{"State.Address"});
Run Code Online (Sandbox Code Playgroud)

所以,沿着这条线(这只是一个测试):

public E FindByIdWithIncludes<E>(int id, string[] includes) where E : class
{
    var entitySet = DataContext.Set<E>();
    DbQuery<E> entityQuery;

    foreach (var include in includes)
    {
        entityQuery = entitySet.Include(include);
    }

    return entityQuery.Find(id); //this is were it breaks
}
Run Code Online (Sandbox Code Playgroud)

可能吗?

Lad*_*nka 8

您不能Find直接使用- Find不适用于包含.你必须使用SingleOrDefault.

首先,您需要为实体定义接口以公开其密钥.

public interface IEntityWithId 
{
    public int Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

接下来,您可以编写带约束的简单方法来访问密钥:

public E FindByIdWithIncludes<E>(int id, string[] includes) 
    where E : class, IEntityWithId
{          

    IQueryable<E> entityQuery = DataContext.Set<E>();

    foreach (var include in includes)
    {
            entityQuery = entityQuery.Include(include);
    }

    return entityQuery.SingleOrDefault(e => e.Id == id); 
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句.你可以使用强类型包含 - 这是一个例子.