【问题标题】:one linq query to load many to many relationship一个 linq 查询加载多对多关系
【发布时间】:2011-07-27 20:17:09
【问题描述】:

有很多类似的问题,我在发布这个问题之前做了我的研究。

我有3张表,是多对多的关系。

帖子:帖子ID、帖子名称

标签:TagId、TagName

PostTag:PostTagID、PostID、TagID

这是我在控制器中的代码。

    public ActionResult List(int page = 1, int record = 10)
    {
        return View((IEnumerable<Post>)GetPosts(page, record));
    }

    public IList<Post> GetPosts(int page = 1, int record = 10)
    {
        var options = new DataLoadOptions();

        options.LoadWith<Post>(p => p.PostTags);
        options.LoadWith<PostTag>(pt => pt.Tag);

        using (var db = new mvc3codesDataContext())
        {
            db.LoadOptions = options;

            return (from p in db.Posts select p).ToList();
        }


    }

这是我的视图文件中的代码。

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.PostID)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.PostName)
        <br />

        @foreach (var pt in item.PostTags)  -----> this part not working. 
        {                                 

        }
    </td>
</tr>

}

它显示了一个帖子列表,但我不知道如何输出标签。

【问题讨论】:

    标签: linq-to-sql many-to-many


    【解决方案1】:

    在您的示例中, pt 是 PostTag,而不是标签本身。在这种情况下,您需要将多对多关系更多地视为 1-0..*-1。在这种情况下,您将访问 pt.Tag.Property。

    【讨论】:

    • 我尝试执行“item.Tags”,但智能感知列表中没有“Tags”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 2017-10-04
    • 1970-01-01
    • 2021-01-30
    相关资源
    最近更新 更多