3

我想只在 .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 中,有一种方法可以声明这一点: Register(System.Reflection.MemberInfo member, System.Linq.Expressions.LambdaExpression 替换) 将替换注册为成员的替换。

4

1 回答 1

1

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

var fullNameSelector = MyExpressions.FullNameSelector;
var query = from o in ctx.Orders.AsExpandable()
            select new
            {
                Id = o.Id,
                FullName = fullNameSelector.Invoke(o)
            };
于 2013-06-10T15:54:26.520 回答