我想只在 .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 替换) 将替换注册为成员的替换。