C# 外键属性赢得';设置不正确

C# 外键属性赢得';设置不正确,c#,asp.net,model-view-controller,foreign-keys,data-annotations,C#,Asp.net,Model View Controller,Foreign Keys,Data Annotations,我之前发布了一篇类似代码的帖子,并更新了模型,使用了一个helper类而不是ViewBag。在数据库更新之前,它似乎很有魅力 这些是我的模型课 [Table("Store")] public class Store { [Key] public int StoreId { get; set; } public string Name { get; set; } public string Address { ge

我之前发布了一篇类似代码的帖子,并更新了模型,使用了一个helper类而不是ViewBag。在数据库更新之前,它似乎很有魅力

这些是我的模型课

[Table("Store")]
    public class Store
    {
        [Key]
        public int StoreId { get; set; }

        public string Name { get; set; }

        public string Address { get; set; }
    }
当我的代码指向db.Purchases.Add(purchase)时,purchase对象的Store属性设置为null。然而,StoreId似乎非常好。我不明白为什么Store对象不会随着StoreId属性而改变,因为我已经用[ForeignKey(“StoreId”)]对它进行了注释。我在哪里搞砸了StoreId和Store之间的连接

更新#2

@model IEnumerable
@{
ViewBag.Title=“Index”;
}
指数

@ActionLink(“新建”、“创建”)

@DisplayNameFor(model=>model.Store.Name) @DisplayNameFor(model=>model.Type) @DisplayNameFor(model=>model.Price) @DisplayNameFor(model=>model.Date) @foreach(模型中的var项目){ @DisplayFor(modelItem=>(item.Store.Name)) @DisplayFor(modelItem=>item.Type) @DisplayFor(modelItem=>item.Price) @DisplayFor(modelItem=>item.Date) @ActionLink(“编辑”,“编辑”,新的{id=item.id})| @ActionLink(“详细信息”,“详细信息”,新的{id=item.id})| @ActionLink(“删除”,“删除”,新的{id=item.id}) }
更新#3

我假设您看不到purchase.Store的任何值,这是因为模型绑定器仅绑定您在中指定的StoreId(当请求从浏览器发送到Web服务器时)

@Html.DropDownListFor(model => model.Purchase.StoreId, new SelectList(Model.Stores.Select( x => new { StoreId = x.StoreId, DisplayName = x.Name.ToString() + " - " + x.Address.ToString()}), "StoreId", "DisplayName"), new { @class = "form-control" })
purchase.Store的填充属于EF。执行此操作时,EF将加载该存储

dbContext.Purchases.Include(x => x.Store).FirstOrDefault(x => x.ID == 1234);
更新:

如果要在后期操作中使用存储对象

    // POST: Purchases/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Purchase purchase)
    {
        if (ModelState.IsValid)
        {
            db.Purchases.Add(purchase);
            db.SaveChanges();
            purchase = dbContext.Purchases.Include(x => x.Store).FirstOrDefault(x => x.ID == purchase.ID); // Not sure why you need Store information at this step.
            return RedirectToAction("Index");
        }

        return View(purchase);
    }

我必须在哪个类中添加此代码?在PurchaseDBContext中?在您的示例中,有两个操作GET和POST。您遇到了哪一个问题?post-one,在post方法中添加代码似乎无法解决问题。我已将代码添加到您的post操作中。但是,我仍然不明白为什么在重定向到索引页时需要存储数据。存储仍然为空,因此在索引页中没有显示存储名称。
        // GET: Purchases/Create
        public ActionResult Create()
        {
            var purchaseHelper = new PurchaseCreateHelper()
            {
                Stores = db.Stores.ToList(),
                Purchase = new Purchase()
            };

            return View(purchaseHelper);
        }

        // POST: Purchases/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Purchase purchase)
        {
            if (ModelState.IsValid)
            {
                db.Purchases.Add(purchase);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(purchase);
        }
        // GET: Purchases
        public ActionResult Index()
        {
            return View(db.Purchases.ToList());
        }
@model IEnumerable<BookKeeper.Models.Purchase>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Store.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Type)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Date)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => (item.Store.Name))
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Type)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Price)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Date)
    </td>
    <td>
        @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
        @Html.ActionLink("Details", "Details", new { id = item.Id }) |
        @Html.ActionLink("Delete", "Delete", new { id = item.Id })
    </td>
</tr>
}

</table>
@Html.DropDownListFor(model => model.Purchase.StoreId, new SelectList(Model.Stores.Select( x => new { StoreId = x.StoreId, DisplayName = x.Name.ToString() + " - " + x.Address.ToString()}), "StoreId", "DisplayName"), new { @class = "form-control" })
dbContext.Purchases.Include(x => x.Store).FirstOrDefault(x => x.ID == 1234);
    // POST: Purchases/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create(Purchase purchase)
    {
        if (ModelState.IsValid)
        {
            db.Purchases.Add(purchase);
            db.SaveChanges();
            purchase = dbContext.Purchases.Include(x => x.Store).FirstOrDefault(x => x.ID == purchase.ID); // Not sure why you need Store information at this step.
            return RedirectToAction("Index");
        }

        return View(purchase);
    }