具有Entity Framework的动态lambda表达式

时间:2015-05-28 06:55:18

标签: c# entity-framework lambda

我有以下实体:

public enum RecordType
{
    Person,
    Company,
    //etc...
}

public class Entity
{
    public int Id {get; set;}
    public RecordType RecordType {get; set;}
    public int PersonId {get; set;}
    public int CompanyId {get; set;}
    public Person Person {get; set;}
    public Company Company {get; set;}
}

根据RecordType,实体将保存在PersonIdCompanyId表格列中。

为了从db加载实体,我以这样的方式使用预先加载:

public Entity Get(Expression<Func<Entity, bool>> where)
{
    return Get(where, x => x.Person,
                      x => x.Company);
}

public Entity Get(Expression<Func<Entity, bool>> where, params Expression<Func<Entity, object>>[] include)
{
    var set = include.Aggregate<Expression<Func<Entity, object>>, IQueryable<Entity>>
              (dbSet, (current, expression) => current.Include(expression));

    return set.Where(where).FirstOrDefault();
}

为了限制发送的SQL语句的大小和复杂性以及db返回的结果集,我想知道是否可以使Get方法看起来像这样:

public Entity Get(Expression<Func<Entity, bool>> where)
{
    return Get(where, x => x.Person.When(x.RecordType == Person),
                      x => x.Company.When(x.RecordType == Company);
}

因此,只会根据RecordType列的值添加与关联表的连接。注意:以上内容不是有效代码,只是为了说明如何实现它。

有没有办法实现这个功能?

0 个答案:

没有答案
相关问题