Linq to sql 如何将LINQ映射到SQL以启用即时加载、返回EntitySet或ICollection?

Linq to sql 如何将LINQ映射到SQL以启用即时加载、返回EntitySet或ICollection?,linq-to-sql,eager-loading,Linq To Sql,Eager Loading,这与我的问题相关(但相当独立): 我曾尝试使用DataLoadOptions强制快速加载,但我无法让它工作 我正在手动编写LinqToSQL映射,并首先遵循本教程: 现在我找到了本教程: 我至少可以发现一个主要的区别。第一个教程建议返回ICollection,第二个EntitySet。由于出现问题,我尝试将代码切换为返回EntitySet,但随后我遇到了需要在视图和控制器中引用System.Data.Linq的问题。我试着这么做,但没有成功。我也不确定这是个好主意 在这一点上,我只想知道一个好的

这与我的问题相关(但相当独立):

我曾尝试使用
DataLoadOptions
强制快速加载,但我无法让它工作

我正在手动编写LinqToSQL映射,并首先遵循本教程:

现在我找到了本教程:

我至少可以发现一个主要的区别。第一个教程建议返回
ICollection
,第二个
EntitySet
。由于出现问题,我尝试将代码切换为返回
EntitySet
,但随后我遇到了需要在视图和控制器中引用System.Data.Linq的问题。我试着这么做,但没有成功。我也不确定这是个好主意


在这一点上,我只想知道一个好的设计应该使用哪种返回类型?我能有一个好的设计并且在特定情况下仍然能够强制快速加载吗?

大量的尝试和错误最终导致了解决方案。可以返回
ICollection
IList
,或者在某些情况下返回
IEnumerable
。有些人认为返回
EntitySet
IQueryable
是个坏主意,我同意,因为它暴露了很多数据源/技术。有些东西返回
IEnumerable
是个坏主意,这似乎要视情况而定。问题是它可以用于延迟加载,这可能是一件好事,也可能不是一件好事

一个反复出现的问题是返回分页结果,并计算页面外的项目总数。这可以通过创建一个
集合页面
()

有关从存储库返回内容的更多信息,请参见:

更重要的是,
DataLoadOptions
可以快速加载!我现在已经对代码进行了太多的重构,我无法100%确定是什么错误导致了
DataLoadOptions
无法工作。据我所知,如果在使用了
DataContext
之后尝试将其添加到
DataContext
中,我会得到一个异常,但它没有这样做。但我发现的是在工作单元模式中思考。然而,出于我的需要(因为我不想从我的存储库返回
EntitySet
IQueryable
),我不打算实现跨存储库的工作单元。相反,我只是将我的存储库方法看作它们自己的小工作单元。我确信这有一些不好的地方(例如,在某些更新场景中,它可能会导致更多的数据库往返),将来我可能会重新考虑。然而,这是一个简单的清洁解决方案

更多信息请点击此处:

这就是我在我的存储库中得到的结果:

public class SqlLocalizedCategoriesRepository : ILocalizedCategoriesRepository
{
    private string connectionString;
    private HttpContextBase httpContext;
    public SqlLocalizedCategoriesRepository(string connectionString, HttpContextBase httpContext) // Injected with Inversion of Control
    {
        this.connectionString = connectionString;
        this.httpContext = httpContext;
    }

    public CollectionPage<Product> GetProductsByLocalizedCategory(string category, int countryId, int page, int pageSize)
    {
        // Setup a DataContext
        using (var context = new DataContext(connectionString)) // Because DataContext implements IDisposable it should be disposed of
        {
            var dlo = new System.Data.Linq.DataLoadOptions();
            dlo.LoadWith<Product>(p => p.ProductSubs); // In this case I want all ProductSubs for the Products, so I eager load them with LoadWith. There's also AssociateWith which can filter what is eager loaded.
            context.LoadOptions = dlo;
            context.Log = (StringWriter)httpContext.Items["linqToSqlLog"]; // For logging queries, a must so you can see what LINQ to SQL generates

            // Query the DataContext
            var cat = (from lc in context.GetTable<LocalizedCategory>()
                       where lc.CountryID == countryId && lc.Name == category
                       select lc.Category).First(); // Gets the category into memory. Might be some way to not get it into memory by combining with the next query, but in my case my next step is that I'm also going to need the Category anyway so it's not worth doing because I'm going to restructure this code to take a categoryId parameter instead of the category parameter.

            var products = (from p in context.GetTable<Product>()
                            where p.ProductCategories.Any(pm => pm.Category.CategoryID == cat.CategoryID)
                            select p); // Generates a single query to get the the relevant products, which with DataLoadOptions loads related ProductSubs. It's important that this is just a query and not loaded into memory since we're going to split it into pages.

            // Return the results
            var pageOfItems = new CollectionPage<Product>
            {
                Items = products.Skip(pageSize * (page - 1)).Take(pageSize).ToList(), // Gets the page of products into memory
                TotalItems = products.Count(), // Get to total count of items belonging to the Category
                CurrentPage = page
            };
            return pageOfItems;
        }
    }
}
公共类SQLLocalizedCategories存储库:iLocalizedCategories存储库
{
私有字符串连接字符串;
私有HttpContextBase httpContext;
公共SqlLocalizedCategoriesRepository(string connectionString,HttpContextBase httpContext)//注入控制反转
{
this.connectionString=connectionString;
this.httpContext=httpContext;
}
公共集合页面GetProductsByLocalizedCategory(字符串类别、int countryId、int page、int pageSize)
{
//设置数据上下文
使用(var-context=new-DataContext(connectionString))//因为DataContext实现了IDisposable,所以应该丢弃它
{
var dlo=new System.Data.Linq.DataLoadOptions();
dlo.LoadWith(p=>p.ProductSubs);//在这种情况下,我希望产品的所有ProductSubs,因此我使用LoadWith急切地加载它们。还有一个可以过滤急切加载的内容的AssociateWith。
context.LoadOptions=dlo;
context.Log=(StringWriter)httpContext.Items[“linqToSqlLog”];//对于日志记录查询,必须使用此选项,以便您可以查看LinqToSQL生成的内容
//查询数据上下文
var cat=(来自context.GetTable()中的lc)
其中lc.CountryID==CountryID&&lc.Name==category
选择lc.Category.First();//将类别放入内存中。与下一个查询结合可能是不将其放入内存的一种方式,但在我的情况下,我的下一步是,无论如何我也将需要该类别,因此不值得这样做,因为我将重新构造此代码,以采用categoryId参数而不是category参数。
var products=(来自context.GetTable()中的p)
其中p.ProductCategories.Any(pm=>pm.Category.CategoryID==cat.CategoryID)
选择p);//生成一个查询以获取相关产品的数据,该查询使用DataLoadOptions加载相关的ProductSub。重要的是,这只是一个查询,而不是加载到内存中,因为我们要将其拆分为页面。
//返回结果
var pageOfItems=新集合页面
{
Items=products.Skip(pageSize*(page-1)).Take(pageSize).ToList(),//将产品页放入内存
TotalItems=products.Count(),//获取属于该类别的项目总数
当前页面=第页
};
返回pageOfItems;
}
}
}