3

这与我的问题相关(但相当独立):Why SELECT N + 1 with no foreign keys and LINQ?

我试过使用DataLoadOptions强制加载,但我没有让它工作。

我正在手动编写我的 LinqToSQL 映射,并且首先遵循本教程: http: //www.codeproject.com/Articles/43025/A-LINQ-Tutorial-Mapping-Tables-to-Objects

现在我找到了这个教程:http: //msdn.microsoft.com/en-us/library/bb386950.aspx

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

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

4

1 回答 1

1

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

一个反复出现的问题是返回分页结果并计算页面外的总项目数。这可以通过创建一个CollectionPage<T>http://www.codetunnel.com/blog/post/104/how-to-properly-return-a-paged-result-set-from-your-repository)来解决

更多关于从这里的存储库返回的内容:

http://www.codetunnel.com/blog/post/103/should-you-return-iqueryablet-from-your-repositories

http://www.shawnmclean.com/blog/2011/06/iqueryable-vs-ienumerable-in-the-repository-pattern/

IEnumerable 与 IQueryable 用于业务逻辑或 DAL 返回类型

List、IList、IEnumerable、IQueryable、ICollection,哪种返回类型最灵活?

更重要的是,DataLoadOptions 可以进行急切加载!我现在已经对我的代码进行了如此多的重组,我不能 100% 确定我做错了什么导致DataLoadOptions无法工作。据我所知,如果我尝试将它添加到使用DataContext后,我应该得到一个例外DataContext,但它没有。我发现的是在工作单元模式中思考。但是,出于我的需要(并且因为我不想返回EntitySetIQueryable来自我的存储库)我不会实现跨存储库工作单元。相反,我只是将我的存储库方法视为他们自己的小型工作单元。我确信这有一些不好的地方(例如,在某些更新场景中它可能会导致更多的数据库往返),将来我可能会重新考虑。然而,这是一个简单干净的解决方案。

更多信息在这里:

https://stackoverflow.com/a/7941017/1312533

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net- mvc-应用程序

这就是我在存储库中的最终结果:

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;
        }
    }
}
于 2012-10-04T06:05:33.050 回答