实体框架必需的外键= db.SaveChanges上的验证错误 [英] Entity Framework Required Foreign Key = validation error on db.SaveChanges

查看:92
本文介绍了实体框架必需的外键= db.SaveChanges上的验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的公司实体有这些类

    public class Company
    {
        public Company()
        {
            this.Users = new HashSet<User>();
            this.Tools = new HashSet<Tool>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }

        public virtual ICollection<User> Users { get; set; }
        public virtual ICollection<Tool> Tools { get; set; }
        [Required]
        public virtual CompanyGroup CompanyGroup { get; set; }
    }

    public class CompanyDto
    {
        public string Name { get; set; }
        public string Address { get; set; }
    }

在CompaniesController中,我添加了一个带有Id参数的附加类,用于此类编辑/更新方法中

in the CompaniesController i've added an additional class with the Id parameter for usage in edit/update methods like this

    public class CompanyViewEditModel : CompanyDto {
        public int Id { get; set; }
    }

编辑方法"如下所示:

        [HttpPost]
        public ActionResult Edit(CompanyViewEditModel companyViewModel)
        {
            if (ModelState.IsValid)
            {
                var company = db.Companies.Find(companyViewModel.Id);
                company.InjectFrom(companyViewModel);
                db.Entry(company).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(companyViewModel);
        }

InjectFrom方法来自ValueInjecter.

The InjectFrom Method is from ValueInjecter.

由于验证异常,一切正常,仅db.SaveChanges调用失败.经过一些挖掘后,我发现他认为该公司无效,因为必须使用CompanyGroup字段,但是如果我使用调试器,即使在InjectFrom调用之后,也要查看该公司变量,一切似乎都很好.相应的公司组在那里.

Everything works as expected only the db.SaveChanges call fails, because of an validation exception. With some digging in the exceptionI've found out that he thinks the company is invalid because the field CompanyGroup is required but if i take a debugger look at the company variable even after the InjectFrom call everything seems to be fine. The corresponding company group is there.

推荐答案

考虑更改模型,因为您不必根据需要标记导航属性.而是像这样添加FK.

Consider changing your model as you shouldn't have to mark the navigational property as required. Instead add a FK like so.

public class Company
{
    public Company()
    {
        this.Users = new HashSet<User>();
        this.Tools = new HashSet<Tool>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public int CompanyGroupId { get; set; }

    public virtual ICollection<User> Users { get; set; }
    public virtual ICollection<Tool> Tools { get; set; }
    public virtual CompanyGroup CompanyGroup { get; set; }
}

这篇关于实体框架必需的外键= db.SaveChanges上的验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆