每次我添加一个新的 App 它都会创建一个新的 AppCategory。我以某种方式认真地搞砸了
代码优先实体框架对象
public class AppCategory
{
public int ID { get; set; }
public string Name { get; set; }
public ICollection<App> apps { get; set; }
}
public class App
{
public int ID { get; set; }
public string Name { get; set; }
public AppCategory Category { get; set; }
}
编辑器模板(我只想制作一个外键 EditorTemplate)
@inherits System.Web.Mvc.WebViewPage
@Html.DropDownList("Category", LIG2010RedesignMVC3.Models.Repo.GetAppCategoriesSelect())
当然还有存储库
public static IEnumerable<SelectListItem> GetAppCategoriesSelect()
{
return (from p in GetAppCategories()
select new SelectListItem
{
Text = p.Name,
Value = p.ID.ToString(),
});
}
public static ICollection<AppCategory> GetAppCategories()
{
var context = new LIGDataContext();
return context.AppCategories.ToList();
}
每次我添加一个新的应用程序它都会创建一个新的 AppCategory 我以某种方式严重搞砸了
添加更多调试信息
@inherits System.Web.Mvc.WebViewPage
@Html.DropDownList("", LIG2010RedesignMVC3.Models.Repo.GetAppCategoriesSelect())
在帖子上给我一条验证信息
Parameters application/x-www-form-urlencoded
Category 1
Name 8
验证错误值“1”无效。
这是有道理的,因为 Category 应该是一个对象而不是整数。
控制器代码 很确定这不是问题,因为它来自 MVCScaffold
[HttpPost]
public ActionResult Create(App d)
{
if (ModelState.IsValid)
{
context.Apps.Add(d);
context.SaveChanges();
return RedirectToAction("Index");
}
return View();
}