Code First Migration和SQL Server Management Studio的问题

问题描述 投票:3回答:1

我正在开发的应用程序的数据库出现问题。我有两个班 - 房子和捐赠。捐赠需要有一个与之相关的房子。

public class House
{
    [Key]
    public int HouseId { get; set; }

    public string AddressLine1 { get; set; }

    public string AddressLine2 { get; set; }

    public string AddressLine3 { get; set; }

}

public class Donation
{
    [Key]
    public int DonationId { get; set; }

    public string TypeOfDonation { get; set; }

    public decimal Amount { get; set; }

    [ForeignKey("Church")]
    public int ChurchId { get; set; }

    [ForeignKey("House")]
    public int HouseId { get; set; }

    public virtual House House { get; set; }
    public virtual Church Church { get; set; }

}

我多次使用Code First Migrations并且它有效,但我遇到了两个错误。我注意到的第一个是在带有捐赠的SQL Server Studio上。它为所有这些提供了无效的列名称

Donation Database Error

然后,当我运行应用程序并尝试将捐赠与房屋关联时,我收到此错误INSERT语句与FOREIGN KEY约束“FK_dbo.Donation_dbo.House_HouseId”冲突。冲突发生在数据库“ChurchDatabase”,表“dbo.House”,列'HouseId'“中。

这是我在DonationController中的Create,我得到了这个错误:

 [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "DonationId,HouseId,TypeOfDonation,Amount,ChurchId")] Donation donation)
    {
        if (ModelState.IsValid)
        {
            db.Donations.Add(donation);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.ChurchId = new SelectList(db.Churches, "ChurchId", "Name", donation.ChurchId);
        return View(donation);
    }

任何人都知道发生了什么事吗?它一直在破坏我的头脑

c# sql-server code-first
1个回答
0
投票

发现我的问题,它在我的视图中:

<div class="form-group">
        @Html.LabelFor(model => model.House.HouseId, "Address", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
           @Html.TextBoxFor(m => m.House.HouseId, new { id = "HouseId" })
           @Html.ValidationMessageFor(model => model.House.HouseId, "", new { @class = "text-danger" })
        </div>
    </div>

它需要是:

<div class="form-group">
        @Html.LabelFor(model => model.HouseId, "Address", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
           @Html.TextBoxFor(m => m.HouseId, new { id = "HouseId" })
           @Html.ValidationMessageFor(model => model.HouseId, "", new { @class = "text-danger" })
        </div>
    </div>

我愚蠢地放下House.HouseId,当它不需要House位时

© www.soinside.com 2019 - 2024. All rights reserved.