Generic Find()包含实体框架 [英] Generic Find() with Includes Entity Framework

查看:94
本文介绍了Generic Find()包含实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前拥有一个完整的通用存储库,但是我缺少一个功能,那就是使用
Include() Find()一起。



所以现在我有:

  public E FindById< E(int id)其中E:class 
{
return DataContext.Set&E;()。Find(id);
}

使用

调用

  var person = PersonRepo.FindById< Person>(personId); 

我想要有类似的东西:

  var person = PersonRepo.FindByIdWithIncludes< Person>(personId,new [] {State.Address}); 

所以,沿着这一行(这只是一个测试)的东西:

  public E FindByIdWithIncludes< E(int id,string [] includes)其中E:class 
{
var entitySet = DataContext。设置< E - 代替;();
DbQuery< E> entityQuery;

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

返回entityQuery.Find(id); //这是破了
}

可以吗?

解决方案

您不能直接使用查找 查找不适用于包含。您必须使用 SingleOrDefault



首先,您需要为实体定义界面以公开其密钥。

  public interface IEntityWithId 
{
public int Id {get;组; }
}

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

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

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

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

返回entityQuery.SingleOrDefault(e => e.Id == id);
}

Btw。您可以使用强类型的包含 - 这里是一个例子


I currently have a complete generic repository but I'm missing one feature and that is to use Include() and Find() together.

So now I have:

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

called using

var person = PersonRepo.FindById<Person>(personId);

I would like to have something similar to:

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

So, something along this lines (this is only a test):

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
}

Is it possible?

解决方案

You cannot use Find directly - Find doesn't work with includes. You must use SingleOrDefault.

First you need to define interface for your entities to expose their key.

public interface IEntityWithId 
{
    public int Id { get; set; }
}

Next you can write simple method with constrain to get access to the key:

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); 
}

Btw. you can use strongly typed includes - here is an example.

这篇关于Generic Find()包含实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆