簡體   English   中英

更新兩個表(父/子)MVC 中的條目時出錯

[英]Error upon updating entries in two tables(Parent/Child) MVC

我有兩個表,具有一對多的關系。 我所做的是,在 Create View(Parent) 中,我添加了一些 Child 字段。因此,在發回控制器時,Parent 字段和 Child Fields 會立即發布。 我正確地收到它們並設法保存到父表,但是我在保存到子表時遇到了問題。

表結構如下:

Parent: ID,DateFrom,DateTo,Name,Version,Status;
Child: ID,ParentID, Item;

這是父控制器 - 創建方法:

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,DateFrom,DateTo,Name,Version,Status")] Parent parent, Array childItems)
        {
            if (ModelState.IsValid)
            {
                db.Parent.Add(parent);
                db.SaveChanges();


                var id = parent.ID;

                foreach (var _item in childItems)
                {
                    var items = new Child()
                    {
                        Item = _item.ToString(),
                        ParentID = id,
                    };
                    db.child.Add(items);
                }
                db.SaveChanges();

                return RedirectToAction("Index");
            }

            return View(parent);
        }

childItems 是一個數組,其中包含子表的 Item 字段的條目。

我想要實現的是在創建父表的條目時(成功發生),我想過濾數組並將子表的條目與相應的父 ID 一起創建。 但是當我運行它時,我收到以下錯誤。

System.Data.Entity.Infrastructure.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'

SqlException: The INSERT statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_dbo.Child_dbo.Child_ParentID". The conflict occurred in database "aspnet-ABC_Automation-20191120105424", table "dbo.Child", column 'ID'.
The statement has been terminated.

我已經調試並注意到在 foreach 循環中, ParentID 持有其各自的值,但我似乎無法弄清楚為什么會拋出錯誤。

有誰知道我該如何解決這個問題?

更新:

父模型:

public class Parent
    {
        [Key]
        public int ID { get; set; }
        public DateTime DateFrom { get; set; }
        public DateTime DateTo { get; set; }
        public string Name { get; set; }
        public string Version { get; set; }
        public string Status { get; set; }

        public ICollection<Child> Items { get; set; }
    }

子模型:

public class Child
    {
        [Key]
        public int ID { get; set; }
        public int ParentID { get; set; }
        public string Item { get; set; }

        [ForeignKey("ParentID")]
        public virtual Parent Items { get; set; }
    }
public class Child
{
[Key]
public int ID { get; set; }
public string Item { get; set; }
public int ParentID { get; set; }

[ForeignKey("Parent")]
public Parent Items { get; set; }
}

嘗試像這樣更改您的 Child 類。 這里的原因是 ParentID 是我們實際的外鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM