我正在编写一个基于标签的 ASP.net 系统。使用以下数据库方案:

Topic <many-many> TagTopicMap <many-many> Tag

基本上,这是我从以下内容中发现的 3NF 方法(toxi): http://www.pui.ch/phred/archives/2005/04/tags-database-schemas.html

这是我的代码片段:

DataLoadOptions options = new DataLoadOptions();
        options.LoadWith<Topic>(t => t.TagTopicMaps);
        options.LoadWith<TagTopicMap>(tt => tt.Tag);
        var db = new lcDbDataContext();
        db.LoadOptions = options;
        db.Log = w;

        var x = from topic in db.Topics
                orderby topic.dateAdded descending
                select topic;

        ViewData["TopicList"] = x.Take(10);

当我执行此命令时,结果很好,但它出现了 11 个单个 SQL 查询,其中一个用于获取前 10 个主题的列表:

    SELECT TOP (10) [t0].[Id], [t0].[title], [t0].[dateAdded]
FROM [dbo].[Topics] AS [t0] ORDER BY [t0].[dateAdded] DESC
-- Context: SqlProvider(Sql2005) Model: AttributedMetaModel Build: 3.5.30729.1 

还有 10 个其他用于单独获取标签详细信息的。

我尝试打开和关闭两个 loadwith 语句,发现发生了以下情况:

loadwith<topic> : no difference for on or off.
loadwith<tagtopicmap>: 11 Queries when on, much more when off.

简而言之,只有第二个 loadwith 选项按预期工作。第一个没有任何效果!

我还尝试将结果集设为ToList()。但更多的问题又出现了:对于标签详细信息部分,它只检索那些唯一的项目,所有这些重复标签(当然,相同的标签可能出现在多个主题中!)都会被查询删除。

最后一件事,以下是我在 aspx 中用于检索数据的代码,如果将结果转为 list(),我将 (IQueryable) 更改为 (IList):

<% foreach (var t in (IQueryable)ViewData["TopicList"])
       {
           var topic = (Topic)t;

    %>
    <li>
        <%=topic.title %> || 
        <% foreach (var tt in (topic.TagTopicMaps))
           { %>
                <%=tt.Tag.Name%>, 
                <%} %>
    </li>
    <%
        }
    %>
有帮助吗?

解决方案

在简短的回答是:LinqToSql有几个怪癖这样,有时你必须使用变通......

在LINQ2SQL LoadWith选项只是导致数据库表之间的内部连接,这样你就可以通过你的rewritting Linq的语句来像(请原谅任何错字力类似的行为,我已经习惯了在VB语法书面方式LINQ的... ):

var x = from topic in db.Topics
        join topicMap in topic.TagTopicMaps
        orderby topic.dateAdded descending
        group topicMap by topicMap.topic into tags = Group;

这句法可能是可怕的错误,但基本的想法是,你强制LINQ2SQL评估主题和TagTopicMaps之间的连接,然后使用分组(或“集团加入”,“让”,等等),以保护对象层次结构中的结果集。

其他提示

设置你的DataContext类为false EnabledDefferedLoad。

您的情况的问题是 Take(10)。这是来自马口中的:

https://connect.microsoft.com/VisualStudio/feedback/details/473333/linq-to-sql-loadoptions-ignored-when-using-take-in-the-query

建议的解决方法是添加 Skip(0)。这对我不起作用,但 Skip(1) 确实有效。虽然可能没什么用,但至少我知道我的问题出在哪里。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top