LINQ to SQL EntitySet中的漏洞抽象

Bra*_*son 6 linq entity-framework linq-to-sql

我遇到了一些dbml生成的类,这些类无法解析为高效的SQL.想象一下,我有一个Accounts表和一个Transactions表,其中每个事务都与一个特定的帐户相关联.我将所有这些加载到dbml中,并弹出一个Account类和一个Transaction类.Account类具有对一组事务的EntitySet引用,这些事务表示该帐户上的所有事务.很公平.

现在假设我只想要当前会计期间的交易.所以我添加一个这样的方法:

public IEnumerable<Transaction> CurrentTransactions
{
    get
    {
        DateTime dtStart = CurrentPeriod;
        DateTime dtEnd = NextPeriod;
        return
            from t in Transactions
            orderby t.date
            where t.date >= CurrentPeriod && t.date <= NextPeriod
            select t;
    }
}
Run Code Online (Sandbox Code Playgroud)

看起来很好,它的工作原理,但SQL不好:

SELECT [t0].[id], [t0].[account_id], [t0].[date], [t0].[description], [t0].[amount], [t0].[sign]
FROM [dbo].[transactions] AS [t0]
WHERE [t0].[account_id] = @p0
Run Code Online (Sandbox Code Playgroud)

即:它将整个事务集拉下来并使用LINQ for Objects处理它.我已经尝试取出where子句,orderby子句,用常量替换日期,它仍然是客户端完成的.

为了比较,我尝试直接从数据上下文调用Transactions集合:

DateTime dtStart = account.CurrentPeriod;
DateTime dtEnd = account.NextPeriod;
IEnumerable<Transaction> trans=
                from t in MyDataContext.Transactions
                orderby t.date
                where t.date >= dtStart && t.date <= dtEnd && t.account_id==iAccountID
                select t;
Run Code Online (Sandbox Code Playgroud)

它工作得很漂亮:

SELECT [t0].[id], [t0].[account_id], [t0].[date], [t0].[description], [t0].[amount], [t0].[sign]
FROM [dbo].[transactions] AS [t0]
WHERE ([t0].[date] >= @p0) AND ([t0].[date] <= @p1) AND ([t0].[account_id] = @p2)
ORDER BY [t0].[date]
Run Code Online (Sandbox Code Playgroud)

毕竟,我有两个问题:

  1. Transactions EntitySet的上述行为是否正确和/或有没有办法解决它?
  2. 如何在我的Account类上实现上述"修复"作为方法.dbml生成的实体类无权访问DataContext.

Pav*_*aev 6

遗憾的是,你无法做到这一点.为LINQ to SQL实体类生成的集合属性不是IQueryable; 因此,对它们执行的任何查询都将使用LINQ to Objects.这是设计的.正如你自己注意到的那样,为了获得有效的查询,你必须Transactions从你的查询中获取DataContext,但你的属性gettor中没有.

此时您的选择是:

  • 使它成为一个带有DataContext参数的方法; 要么
  • 使用反射hackery来检索上下文 - 实体本身并不存储它,但是EntitySet它实际上是存在的,虽然是间接的 - 当然这是版本特定的,容易破坏等等.

据我所知,实体框架没有这个限制,因为它的集合属性是ObjectQuery<T>- 这是IQueryable.