gpt4 book ai didi

c# - Expression> Entity Framework 计算字段

转载 作者:行者123 更新时间:2023-11-30 17:53:41 24 4
gpt4 key购买 nike

我只想在 .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; }
}

当我查询订单 (ctx.Orders.Select(...)...) 时,应连接客户表并填充 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 成员,System.Linq.Expressions.LambdaExpression 替换)将替换注册为成员的替换。

最佳答案

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

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

关于c# - Expression<Func<T,V>> Entity Framework 计算字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17026548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com