实体框架计算字段由Expression>

本文关键字:Func Expression 框架 计算 字段 实体 | 更新日期: 2023-09-27 18:17:49

我想只在。net代码中创建计算字段,而不需要在sql中定义列。

例如:

public class Customer
{
    public int Id { get; set; }            
    public string FirstName { get; set; }            
    public string LastName { get; set; }    
    public DateTime BirthDate { get; set; }
}
public class Order
{
    public int Id { get; set; }    
    public Customer Customer { get; set; }            
    public int CustomerId { get; set; }    
    public static Expression<Func<Customer, int>> CustomerBirthYear_Exp = a => a.BirthDate.Year;    
    /// Populated by CustomerBirthYear_Exp
    public int CustomerBirthYear { get; private set; }            
    public static Expression<Func<Customer, string>> CustomerLastName_Exp = a => a.LastName + " " + a.FirstName;    
    /// Populated by CustomerLastName_Exp
    public string CustomerFullName { get; private set; }
}

当我查询Order (ctx.Orders.Select(…)…)时,Customer表应该被连接,CustomerBirthYear和CustomerFullName应该被填充。相当于

        from o in ctx.Orders
        join a in ctx.Customers on o.CustomerId equals  a.Id
        select new
                {
                    o.Id,
                    CustomerFullName = a.LastName + " " + a.FirstName,
                    CustomerBirthYear_Exp = a.BirthDate.Year
                };

是否有任何方法可以通过为特定成员定义自定义表达式来实现这一点?在另一个ORM中,有几种方法可以声明:(System.Reflection登记。MemberInfo成员,System.Linq.Expressions.LambdaExpression替换)

实体框架计算字段由Expression<Func<T,V>>

不,目前不可能。我见过的最接近的是使用LinqKit来构建可重用的"选择器",这些选择器太长/太常见而不想在代码中重复。它最终看起来像:

var fullNameSelector = MyExpressions.FullNameSelector;
var query = from o in ctx.Orders.AsExpandable()
            select new
            {
                Id = o.Id,
                FullName = fullNameSelector.Invoke(o)
            };