c# - 将 linq-to-sql 表达式的一部分分解为一个单独的函数

标签 c# .net linq-to-sql

我有两个实体类:

public class Invoice
{
  public int ID { get; set;}
  public int Amount { get { return InvoiceLines.Sum(il => il.Amount); }}
  public EntitySet<InvoiceLines> InvoiceLines {get;set;};
}

public class InvoiceLine
{
  public Invoice Invoice {get;set;}
  public int InvoiceID {get;set;}
  public int Amount {get;set;}
  public string SomeHugeString {get;set;}
}

(真正的类是 sqlmetal 生成的,我在这里缩短了它以达到目的)。

查询所有金额:

var amounts = from i in invoice select i.Amount;

这将导致所有发票行延迟加载,每张发票调用一个数据库。我可以使用数据加载选项解决它,但这会导致读取整个 InvoiceLine 对象,包括 SomeHugeString

在查询中重复金额计算会得到一个好的SQL翻译:

var amounts = from i in invoice select i.InvoiceLines.Sum(il => il.Amount);

我希望 linq-to-sql 以某种方式从函数/属性中获取表达式树的一部分。有没有办法重写 Invoice.Amount 以便第一个金额查询将提供与第二个相同的 SQL 转换?

最佳答案

您可以使用来自 LINQKitAsExpandable() 做类似的事情:

Expression<Func<Invoice, int>> getAmount =
    i => i.InvoiceLines.Sum(il => il.Amount);

var amounts = from i in invoice.AsExpandable() select getAmount.Invoke(i);

关于c# - 将 linq-to-sql 表达式的一部分分解为一个单独的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7945685/

相关文章:

c# - 特性信息有什么优势?

c# - 始终运行网络服务

C#相当于Java资源

c# - 在 C# 中为 Xamarin 禁用泛型

c# - 使用 LINQ 在 C# 中的基于服务的数据库中搜索值是否存在

asp.net-mvc - 如何使用 LinqToSQL 实现对 ASP.NET MVC 2 中的数据注释验证功能的自定义控制?

c# - 如何在 asp.net 中创建多 View 控件并在运行时对其进行操作?

.net - 如何将 Excel 日期序列号转换为 .NET DateTime?

c# - 为什么使用 "as"运算符进行转换会导致使用 C# 动态转换的对象为 null

c# - LINQ to SQL - 自定义函数