문제

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
도움이 되었습니까?

해결책

당신이 뭔가를 발견했는데, 여전히 검색 할 수있는 사람이 거기에서 다른 사람들을 위해, 이것을보십시오 :

https://github.com/workshirt/wscoachmarksview

다른 팁

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.

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

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.

뷰를 사용하여 가장 중요한 목록이나 라이브러리의 항목을 볼 수 있습니다. 예를 들어 특정 부서에서 특정 부서에 적용되는 라이브러리의 파일의보기 또는 특정 사람이 만든 목록의 항목을 만들 수 있습니다. 목록이나 라이브러리에서 볼 수 있습니다.

각 목록 또는 라이브러리에는 적어도 하나의 뷰가 있습니다. 브라우저에서 이러한 뷰를 수정하고 새보기를 만드는 것이 좋습니다. 예를 들어 작업 목록에는 모든 작업 및 내 작업과 같은 여러 뷰가 포함됩니다. 목록의 항목이 정렬되는 방식을 변경하여 이러한 뷰를 수정할 수 있습니다. 또는 불완전한 작업만을 보여주는 새보기를 만들 수 있습니다.

요구 사항에 대해서는 -> 수정 -> 스타일 아래에서 -> 원하는 스타일을 선택할 수 있습니다.

목록 / 라이브러리보기의 스타일에 대한 자세한 내용은 아래 링크를 살펴보십시오.

목록 또는 라이브러리의보기 생성, 변경 또는 삭제

위의 링크에서 아래로 스크롤하여 "뷰 설정"에서 "스타일"이라는 섹션을 찾아서 요구 사항을 수행하는 데 도움이 될 수 있습니다.

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top