【问题标题】:Making multiple models cast an ID using Entity Framework使用实体框架使多个模型转换一个 ID
【发布时间】:2015-07-15 21:37:29
【问题描述】:

我是使用实体框架的新手。我已经添加了我的模型,我需要在一个视图页面中使用我的两个模型/表格。为此,我将其添加到了我的 AccountViewModels.cs 页面:

  public class category_menuitem
{
    public Category Category { get; set; }
    public MenuItem MenuItem { get; set; }

}

我正在尝试使用这两个模型/表中的值。

我的查看页面:

using System.Data.SqlClient
@model IEnumerable<YourGoGetterV1.Models.category_menuitem>
@{
    ViewBag.Title = "Show Menu" - ViewBag.restaurant_id;
}

<h2>ShowMenu</h2>


<div class="jumbotron">

    @foreach (var item in Model)
    {
        <div><strong>@Html.DisplayFor(item1 => item.Category.Name)</strong>
        <div>@Html.DisplayFor(item1 => item.Category.Description)</div>
    @{ 
        using (var context = new YourGoGetterContext())
        {
            SqlParameter sa = new SqlParameter("@p0", ViewBag.restaurant_id);
            var menu_items = context.MenuItems.SqlQuery("Select * FROM MenuItems where restaurant_id = @p0", sa).ToList();
            var test = "DID IT WORK??";
        }
    }


        </div>
    }
</div>

控制器:

public ActionResult ShowMenu(string id, int restaurant_id)
{
    ViewBag.Id = id;
    ViewBag.restaurant_id = restaurant_id;
    return View(Models.category_menuitem.ToList((object(id)));

}

我想转换 ID,以便它为传入不同 ID 的内容创建不同的 URL。但是我有两个问题。

1) 我什至不能放入 Models.Category_menuitem.ToList() 因为“方法 'ToList' 没有重载需要 1 个参数”

2)Models.Category_menuitem 不包含 ToList 的定义。

我该怎么办?

【问题讨论】:

    标签: c# asp.net-mvc entity-framework model-view-controller


    【解决方案1】:

    我认为你应该做不同的事情。模型应该包含您在视图中使用的数据。模型中的数据库请求也是如此,并将模型提供给视图以显示其中的数据。不要在视图中执行 SQL 请求。由于 C# 命名约定,您还应该始终以大写字母编写类名。

    如果我理解正确,您想显示一个带有类别的菜单栏或类似的东西,并且每个类别都有很多菜单项?

    只需像这样创建一个模型菜单项:

    public class MenuItems {
    public List<Category> Categories{get;set;}
    }
    

    和这样的模型类别:

        public class Category {
    public string CategoryName {get;set;}
    public List<MenuItem> MenuItems {get;set;}
    }
    

    用数据填充模型并将 MenuItems 模型提供给视图。在视图中,您可以执行以下操作:

    @foreach (var category in Model.Categories)
        {
    
    foreach (var menuItem in category.MenuItems)
        {
    
    }
    }
    

    我希望这会有所帮助;)

    到这部分代码:

    var menu_items = context.MenuItems.SqlQuery("Select * FROM MenuItems where restaurant_id = @p0", sa).ToList();
    

    我不确定你想做什么。您正在查询数据库中应该已经在模型中的数据还是我错了?但如果你想使用 EF,你会写:

    var items = context.Menuitems.Where(m => m.restaurant_id == id).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多