Entity Framework Required Foreign Key = validation error on db.SaveChanges

霸气de小男生 提交于 2021-01-27 19:03:51

问题


I have these classes for my Company Entity

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

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

The Edit Method looks like that:

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

The InjectFrom Method is from ValueInjecter.

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.


回答1:


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


来源:https://stackoverflow.com/questions/13067288/entity-framework-required-foreign-key-validation-error-on-db-savechanges

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!