[asp.net-mvc]外键添加到 MVC 中的数据库时的问题

发布时间: 2017/3/25 1:59:34
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我有一个函数 (addItem) 这是页数将新行添加到我的数据库。但该函数在运行时,它给了我这个错误︰

{"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK1\". The conflict occurred in database \"C:\\USERS\\ALAL0006\\DOWNLOADS\\SOA PROJEKT\\SOA PROJEKT\\SOA PROJEKT\\APP_DATA\\DATABASE1.MDF\", table \"dbo.Category\", column 'Id'.\r\nThe statement has been terminated."}

控制器︰

public ActionResult Create()
    {
        IEnumerable<SelectListItem> categories = tbl.Category.Select(c => new SelectListItem
        {
            Value = SqlFunctions.StringConvert((double)c.Id).Trim(),
            Text = c.Namn
        });
        //ViewBag.Category = new SelectList(tbl.Category, "Id", "Namn");
        ViewBag.Id = categories;
        return View();
    }
    [HttpPost]
    public ActionResult Create(Vara newItm)
    {
        if (ModelState.IsValid)
        {
            srvc.addItem(newItm.Namn, newItm.Pris, newItm.CategoryID);
            return RedirectToAction("Create");
        }
        else
        {
            return View();
        }
    }

服务︰

public void addItem(string name, int price, int ctgID)
    {
        Database1Entities1 tbl = new Database1Entities1();
        Vara newItm = new Vara() {

            Namn = name,
            Pris = price,
            CategoryID = ctgID,

        };
        tbl.Vara.Add(newItm);
        try
        {
            tbl.SaveChanges();
        }

cshtml 文件︰

        <div class="form-group">
        @Html.LabelFor(model => model.Namn, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Namn)
            @Html.ValidationMessageFor(model => model.Namn)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Pris, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Pris)
            @Html.ValidationMessageFor(model => model.Pris)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CategoryID, "CategoryID", new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Id", "Välj kategori")
            @Html.ValidationMessageFor(model => model.CategoryID)
        </div>
    </div>

DB 类别︰

CREATE TABLE [dbo].[Category] (
[Id]   INT           IDENTITY (1, 1) NOT NULL,
[Namn] VARCHAR (MAX) NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC));

项目数据库︰

CREATE TABLE [dbo].[Vara] (
[Id]         INT           IDENTITY (1, 1) NOT NULL,
[Namn]       VARCHAR (MAX) NOT NULL,
[Pris]       INT           NOT NULL,
[CategoryID] INT           NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK1] FOREIGN KEY ([CategoryID]) REFERENCES [dbo].[Category] ([Id]));

我不能确定我要怎样才能解决这个问题。有什么想法?

解决方法 1:

你的问题是,在 POST 方法的值 newItm.CategoryID0 (默认为 int ) 因为你从来不会生成窗体控件的属性 CategoryID ( <select> 您生成属性的元素 Id )。

您需要更改到视图中的代码 (总是使用强类型 xxxFor() 方法)

@Html.DropDownListFor(m => m.CategoryID, (IEnumerable<SelectListItem>)ViewBag.Id, "Välj kategori")

此外,你需要修改你的 POST 方法,重新分配的值 ViewBag.Id 如果 ModelState 是无效和你返回的视图,否则为将引发异常

[HttpPost]
public ActionResult Create(Vara newItm)
{
    if (ModelState.IsValid)
    {
        ....
    }
    ViewBag.Id = ... // same code as used in the GET method.
    return View(newItm);
}

但是更好的方法是使用视图模型 (请参阅在 MVC 中的视图模型是什么?)。

public class VaraVM
{
    public int? ID { get; set; }
    ....
    [Display(Name = "Category")]
    [Required(ErrorMessage = "Please select a category")]
    public int SelectedCategory { get; set; }
    public IEnumerable<SelectistItem> CategoryList { get; set; }   
}

并在视图中

@Html.DropDownListFor(m => m.SelectedCategory , Model.CategoryList, "Välj kategori")

并在控制器中

public ActionResult Create()
{
    VaraVM model = new VaraVM();
    ConfigureViewModel(model);
    return View(model);
}

[HttpPost]
public ActionResult Create(VaraVM model)
{
    if (!ModelState.IsValid)
    {
        ConfigureViewModel(model);
        return View(model);  
    }
    // map the view model to a new instance of the data model
    // save and redirect
}

private void ConfigureViewModel(VaraVM model)
{
    model.CategoryList = .... // your query
}
赞助商