【问题标题】:Error upon updating entries in two tables(Parent/Child) MVC更新两个表(父/子)MVC 中的条目时出错
【发布时间】:2019-11-25 06:18:09
【问题描述】:

我有两个表,ParentChild 具有一对多的关系。我所做的是,在创建视图(父)中,我添加了一些子字段。因此,在发回控制器时,父字段和子字段同时发布。我正确接收它们并设法保存到父表,但是我在保存到子表时遇到问题。

表结构如下:

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 字段的条目。

我想要实现的是在创建父表的条目时(成功发生),我想过滤数组并与相应的 ParentID 一起创建子表的条目。但是当我运行它时,我收到以下错误。

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; }
    }

【问题讨论】:

  • 发布您的create table script,好像您已将foreign key 与同一张表申请primary key
  • 嗨@Vishalmodi 请看上面的补充,谢谢
  • @Prishen 你能检查一下 action 方法中的 childItems 是否不为空吗?您会附上数组及其值的屏幕截图吗?
  • 嗨@JerdineSabio 是的,我确实检查过了,它正在正确返回值
  • @Prishen,你已经更新了模型,但我想看看你的 table 脚本

标签: c# asp.net-mvc entity-framework


【解决方案1】:
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 是我们的实际外键。

【讨论】:

  • 那是声明外键的错误方式,这会引发错误。上面声明的方式不会引发与外键有关的任何错误。 codeproject.com/Articles/319366/…
  • 您能分享一下您遇到的错误吗?因为外键后面括号里的名字应该和变量名一样。
  • System.InvalidOperationException: 'The property 'ID' cannot be configured as a navigation property. The property must be a valid entity type and the property should have a non-abstract getter and setter. For collection properties the type must implement ICollection&lt;T&gt; where T is a valid entity type.' 当编译器在 Create Method 中点击 Parent 保存部分时抛出此错误。
  • 这里您使用父类作为导航属性,因此您需要从原始代码中删除虚拟关键字。有关使用外键导航的更多详细信息,您可以在此处查看entityframeworktutorial.net/code-first/…
  • 100% 正确,我已经纠正了这个问题,一切似乎都正常。谢谢@Bansari
猜你喜欢
  • 2021-09-04
  • 1970-01-01
  • 2020-06-28
  • 1970-01-01
  • 1970-01-01
  • 2018-02-20
  • 1970-01-01
  • 2016-02-04
  • 1970-01-01
相关资源
最近更新 更多