在我工作的MVC项目中,我有一个kendo dropDownList,它调用我的服务器Action来执行任何读取操作(包括过滤):
ServiceRequestAssociabili([DataSourceRequest] DataSourceRequest request, int? idServiceRequestOriginale)
小部件绑定了2个属性: IdServiceRequest(value)和IdServiceRequestDescrizione(text)。
IdServiceRequest是实体ID,IdServiceRequestDescrizione是我在实体的Partial类中定义的计算列
public string IdServiceRequestDescrizione
{
get
{
if (TipologiaChiamata.IdTipologiaChiamata != (int)Enums.TipologiaChiamata.Automatica)
{
return IdServiceRequest + " " + Note;
}
else
{
return IdServiceRequest + " " + Email.EmailOggetto;
}
}
}
为了创建正确的linq查询来执行过滤器,我创建了一个System.Linq.Expression,它将我的实体转换为包含2个字符串属性的DTO:
Expression<Func<ServiceRequest, DTO>> funcError = s => new DTO
{
IdServiceRequest = s.IdServiceRequest,
IdServiceRequestDescrizione = s.IdServiceRequestDescrizione
};
然后我使用这个表达式来投射我的IQueryable:
var srq = _serviceRequestRepository.GetByParametersAsQueryable(idServiceRequestOriginale: idServiceRequestOriginale, senzaTicketAssociato: true).Select(funcError).ToList();
如果我在部分中定义IdServiceRequestDescrizione而不是在System.Linq.Expression中定义它,则不会抛出任何错误,一切正常。
Expression<Func<ServiceRequest, DTO>> func = s => new DTO
{
IdServiceRequest = s.IdServiceRequest,
IdServiceRequestDescrizione = s.TipologiaChiamata.IdTipologiaChiamata != (int)EntityModel.Enums.TipologiaChiamata.Automatica ? s.IdServiceRequest + " " + s.Note : s.IdServiceRequest + " " + s.Email.EmailOggetto
};
有人可以给我一个关于这种行为的专业解释吗?为什么我无法在linq Expression中引用自定义属性?
答案 0 :(得分:1)
计算列在C#中实现,但EF仅在数据库模型上运行(从/转换为SQL)。
如果您将方法调用的顺序颠倒过来
,您的代码应该有效.ToList().Select(funcError);
即。首先将记录转换为C#实体对象,然后可以访问计算列。 (我通常使用NHibernate,但问题是一样的)
答案 1 :(得分:0)
有一些选择:
1)Linq.Tranlations Linq.Tranlations
允许你写这样的东西:
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
private static readonly CompiledExpression<Customer, string> fullNameExpression
= DefaultTranslationOf<Customer>.Property(e => e.FullName).Is(e => e.FirstName + " " + e.LastName);
[NotMapped]
public string FullName
{
get { return fullNameExpression.Evaluate(this); }
}
}
var customers = ctx.Customers
.Select(c => new
{
FullName = c.FullName
})
.WithTranslations();
2)DelegateDecompiler DelegateDecompiler
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
[NotMapped]
[Computed]
public string FullName
{
get { return FirstName + " " + LastName; }
}
}
var customers = ctx.Customers
.Select(c => new
{
FullName = c.FullName
})
.Decompile();