The relationship could not be changed because one or more of the foreign-key properties is non-nullable

前端 未结 20 1017
情书的邮戳
情书的邮戳 2020-11-22 04:44

I am getting this error when I GetById() on an entity and then set the collection of child entities to my new list which comes from the MVC view.

The

20条回答
  •  有刺的猬
    2020-11-22 05:13

    I just had the same error. I have two tables with a parent child relationship, but I configured a "on delete cascade" on the foreign key column in the table definition of the child table. So when I manually delete the parent row (via SQL) in the database it will automatically delete the child rows.

    However this did not work in EF, the error described in this thread showed up. The reason for this was, that in my entity data model (edmx file) the properties of the association between the parent and the child table were not correct. The End1 OnDelete option was configured to be none ("End1" in my model is the end which has a multiplicity of 1).

    I manually changed the End1 OnDelete option to Cascade and than it worked. I do not know why EF is not able to pick this up, when I update the model from the database (I have a database first model).

    For completeness, this is how my code to delete looks like:

       public void Delete(int id)
        {
            MyType myObject = _context.MyTypes.Find(id);
    
            _context.MyTypes.Remove(myObject);
            _context.SaveChanges(); 
       }    
    

    If I hadn´t a cascade delete defined, I would have to delete the child rows manually before deleting the parent row.

提交回复
热议问题