我有以下实体:
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
,实体将保存在PersonId
或CompanyId
表格列中。
为了从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
列的值添加与关联表的连接。注意:以上内容不是有效代码,只是为了说明如何实现它。
有没有办法实现这个功能?