使用 LINQ to SQL 在 ASP.NET MVC 中建模多对多关系

发布于 2024-09-04 04:39:40 字数 666 浏览 7 评论 0原文

我一直在阅读和观看有关 MVC 的视频,但我开始感到有点困惑。简单的教程太简单了,它们似乎只涉及一个数据库表。哎呀呀!

高级教程假设存在大量知识,但我在遵循这些知识时遇到了困难。更不用说,有 15 种方法可以对数据库进行建模,但没有人愿意解释为什么他们这样做或那样做。

因此,我正在寻找一个简单的教程或解释,说明您将经历什么过程来设计一个涉及多对多关系的简单 CRUD 应用程序,如下所述。我可能没有提供足够的信息,因此请随时请求更新。

更新: 我有兴趣查看 Linq To Sql 解决方案。

我浏览了 nerddinner PDF,我的模型必须与他的有点不同。我想要与我的膳食和成分建立多对多关系。他只是在晚餐和回复中使用一对多。此外,他从未展示过如何将回复附加到他的晚餐模型上。这本质上是我遇到的问题。为什么我的膳食模型不包含成分列表?我有适当的外键。我不确定在哪里或如何设置它,以便如果我想在详细信息视图或其他东西上打印它们,我可以通过膳食模型访问成分。

餐食

  • ID
  • 标题
  • 描述

成分

  • ID
  • 名称

餐食成分

  • Id_Meal
  • Id_Ingredient

I've been reading and watching videos about MVC and I'm starting to get a little confused. The simple tutorials are far too simple and they seem to only involve a single database table. Whoopty doo!

The advanced tutorials assume a lot of knowledge is present and I have trouble following those. Not to mention, there are 15 ways to model your database and nobody wants to explain why they do it this way or that way.

So, I'm looking for a simple tutorial or explanation of what process you would go through to design a simple CRUD application that involves a many-to-many relationship, explained below. I may not have provided enough information so feel free to request updates.

Updates:
I would be interested in seeing a Linq To Sql solution.

I went through the nerddinner PDF and my model has to be a little different than his. I want a many-to-many relationship with my Meal and my Ingredients. He just uses a 1-to-many with his Dinner and RSVPs. Also, he never shows how he attached the RSVPs to his Dinner model. This is essentially the problem I'm having. Why is it that my Meal model does not contain a list of Ingredients? I have the proper foreign keys in place. I'm not sure where or how I would set it up so that I can access the ingredients through the Meal model if I wanted to print them on the details view or something.

Meals

  • Id
  • Title
  • Description

Ingredients

  • Id
  • Name

Meals-Ingredients

  • Id_Meal
  • Id_Ingredient

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

北陌 2024-09-11 04:39:40

在我当前的项目中,有很多这种关系的例子。我正在使用 MVC 1 和 LINQ-to-SQL。我当时所经历的挫败感与你现在所经历的完全一样。最大的障碍是接受 LINQ-to-SQL 不直接管理多对多关系的事实,但要理解它不需要这样做来获取所需的信息。

让我们从 CRUD 中的 R 开始,因为它是演示需要做什么的最简单方法。现在,我建议创建一个强类型视图模型,只是为了简化聚合视图数据的任务,并简化将膳食数据分配给“详细信息”视图:

public class MealDetailsViewModel
{
    public int Id_Meal { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }

    private List<Ingredient> _Ingredients = new List<Ingredient>();
    public List<Ingredient> Ingredients
    {
       get { return _Ingredients; }
       set { _Ingredients = value; }
    }
}

要检索膳食及其成分列表,这是控制器方法:

public ActionResult Details (int mealID)
{
    Meal result = DataContext.Meals
        .Where(a => a.Id_Meal == mealID)
        .SingleOrDefault();

    MealDetailsViewModel viewModel = new MealDetailsViewModel
    {
        Id_Meal = result.Id,
        Title = result.Title,
        Description = result.Description,
        Ingredients = result.Meals-Ingredients
            .Where(a => a.Id_Meal == mealID)
            .Select(a => a.Ingredient)
            .ToList()
    };

    return View(viewModel);
}

如前所述,LINQ-to-SQL 不直接支持多对多关系,这就是为什么您无法直接从 Meal 中看到 Ingredients 实体。但是,如控制器操作方法中所示,您可以从 Meal 实体访问关联实体 (Meals-Ingredients)。从关联实体中,您可以访问成分实体以获取成分列表。该视图看起来像这样:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="ViewPage<MealDetailsViewModel>" %>

<asp:Content ID="mainMealDetails" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%= Model.Title %></h2>
    <h3><%= Model.Description %></h3>
    <br />
    <p>Ingredients:</p>
    <ul>
        <% foreach(Ingredient item in Model.Ingredients) 
           { %>
            <li><%= item.Name %></li>
        <% } %>
    </ul>
    <br />
    <%= Html.ActionLink("Update", "Edit", new { id = Model.Meal_ID }) %> |
    <%= Html.ActionLink("Add Ingredient", "IngredientCreate", new{ id = Model.Meal_ID }) %> |
    <%= Html.ActionLink("Delete", "Delete", new { id = Model.Meal_ID }) %> |
    <%= Html.ActionLink("Back to Menu List", "Index") %>
</asp.Content>

如果您的数据库架构正确设置了所需的外键关系,则此方法应该为您提供所需的结果。

I have many examples of this type of relationship in my current project. I'm using MVC 1 and LINQ-to-SQL. I went through exactly the same frustration then as you are experiencing now. The biggest hurdle is accepting the fact that LINQ-to-SQL doesn't directly manage many-to-many relationships, but understanding that it doesn't need to in order to get the information you require.

Let's start with the R in CRUD, since it's the easiest way to demonstrate what needs to be done. Now, at this point I would recommend creating a strongly-typed view model, just to ease the task of aggregating your view data and to simplify the assignment of the meal data to the Details view:

public class MealDetailsViewModel
{
    public int Id_Meal { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }

    private List<Ingredient> _Ingredients = new List<Ingredient>();
    public List<Ingredient> Ingredients
    {
       get { return _Ingredients; }
       set { _Ingredients = value; }
    }
}

To retrieve a meal and its list of ingredients, here's the controller method:

public ActionResult Details (int mealID)
{
    Meal result = DataContext.Meals
        .Where(a => a.Id_Meal == mealID)
        .SingleOrDefault();

    MealDetailsViewModel viewModel = new MealDetailsViewModel
    {
        Id_Meal = result.Id,
        Title = result.Title,
        Description = result.Description,
        Ingredients = result.Meals-Ingredients
            .Where(a => a.Id_Meal == mealID)
            .Select(a => a.Ingredient)
            .ToList()
    };

    return View(viewModel);
}

As previously stated, LINQ-to-SQL doesn't directly support many-to-many relationships, which is why you cannot see the Ingredients entity directly from Meal. However, as illustrated in the controller action method, you can access the association entity (Meals-Ingredients) from the Meal entity. From the association entity, you can access the Ingredients entity to get the list of ingredients. The view would look something like this:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="ViewPage<MealDetailsViewModel>" %>

<asp:Content ID="mainMealDetails" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%= Model.Title %></h2>
    <h3><%= Model.Description %></h3>
    <br />
    <p>Ingredients:</p>
    <ul>
        <% foreach(Ingredient item in Model.Ingredients) 
           { %>
            <li><%= item.Name %></li>
        <% } %>
    </ul>
    <br />
    <%= Html.ActionLink("Update", "Edit", new { id = Model.Meal_ID }) %> |
    <%= Html.ActionLink("Add Ingredient", "IngredientCreate", new{ id = Model.Meal_ID }) %> |
    <%= Html.ActionLink("Delete", "Delete", new { id = Model.Meal_ID }) %> |
    <%= Html.ActionLink("Back to Menu List", "Index") %>
</asp.Content>

If your database schema is correctly set up with the foreign key relationships you require, this approach should give you the outcome you're looking for.

ˉ厌 2024-09-11 04:39:40

我强烈推荐 Steve Sanderson 的“Pro ASP.NET MVC Framework”。这是迄今为止我见过的最好的 ASP.NET MVC 指南,在我看来比 MSoft 团队编写的 Wrox 书好得多。如果你想进入的话,非常值得花钱。

亚马逊链接

I highly recommend Steve Sanderson's 'Pro ASP.NET MVC Framework'. It's by far the best ASP.NET MVC guide I've seen, and in my opinion much better than the Wrox book by the MSoft team. Well worth the money if you want to get into it.

Amazon Link

仙气飘飘 2024-09-11 04:39:40

我找到的唯一解决方案是使用 PLINQ。据我所知,它并不完美。

我手动使用“PLINQ方法”: http ://www.codeproject.com/KB/linq/linq-to-sql-many-to-many.aspx

不过我同意,我讨厌一遍又一遍地编写所有这些代码。这不是一个“干净”的解决方案。

The only solution I found was using PLINQ. It isn't perfect as far as I know though.

I use the "PLINQ method" manually: http://www.codeproject.com/KB/linq/linq-to-sql-many-to-many.aspx

I agree though, I hate writing all that code over and over again. It isn't a "clean" solution.

花开雨落又逢春i 2024-09-11 04:39:40

你不会把一切都放在银盘上。你必须亲自经历地狱

就像我和 Ruby on Rails 一样 - 每次我看到示例片段或示例应用程序 - 它看起来超级简单和整洁。但是 - 因为我自己从未真正创造过任何东西,所以我什至不知道从什么开始。

所以 - 只需阅读一些书籍示例应用程序。然后——创造一些东西。这种感觉(从什么开始,如何构建等)很快就会消失。

后来——不要忘记第二个极端——感觉你知道你必须知道的一切。 :)


是的 - 你没有提供足够的信息。有各种各样的路要走。我相信 - 您不会想听到先进的领域驱动设计方法。您也不希望在 html 标记旁边看到 Sql。只有您知道“上下文' 并且可以决定什么是必要的、什么是好的、什么是不需要的。

You won't get everything on silver plate. You will have to go through hell of wtf yourself.

It's like with me and Ruby on Rails - every time i see sample snippet or sample application - it seems super duper simple and neat. But - because I've never actually created anything myself, i got no ideas with what even to start.

So - just go through some books and sample applications. Then - create something. This feeling (with what to start, how to structure etc.) will disappear quite soon.

Later on - don't forget about second extreme - feeling that you know everything you have to know. :)


And yeah - you did not provide enough information. There's various paths to go by. I believe - you won't want to hear advanced domain driven design approaches. Neither you want to see Sql right next to html markup. Only you know 'the context' and can decide what's necessary, good and what's not.

失眠症患者 2024-09-11 04:39:40

我建议您查看专业 ASP.NET MVC 1.0。有一个完整的免费章节可以介绍实际应用程序的一些设置。

并查看 http://www.nerddinner.com/ 查看成品。

这是一个非常简单的 MVC 应用程序,如果您获得这本书,您可以按照它从概念到成品。

I suggest you check out Professional ASP.NET MVC 1.0. There is an entire free chapter available that walks through some of the setup for a real application.

And take a look at http://www.nerddinner.com/ to see the finished product.

This is a very simple MVC application and if you get the book you can follow it from concept to finished product.

双手揣兜 2024-09-11 04:39:40

我发现 Steven Walther 对于 ASP.NET MVC 版本 1 有一些很棒的教程,假设您正在使用第一个版本,因为版本 2 尚未发布(目前为 RC)。第一个工作教程 从这里开始,您应该能够从那里找到其余部分。如果您在该网站上搜索他的博客,他还会提供很多好的建议。

此外,本教程的大部分内容都涵盖 VB 和 C#(如果这对您很重要)。

I find Steven Walther has some great tutorials for asp.net MVC version 1, assuming you're working with the first version as version 2 is not released yet (RC currently). The first working tutorial starts here and you should be able to find the rest from there. He also has lots of good tips if you search through his blog on that site.

Also most of this tutorials cover VB and C#, if that's important to you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文