I am a beginner in the field of IT, more particularly in the C # language, I use the ASP.Net MVC framework.
I am working on an online restaurant web application, I will be the administrator of the site, so it is I who manage any addition of restaurants or menus.
For the moment I am working on my two classes Restaurant
and Menu
, they are linked by a relation 1:n
and I use the database first approach.
So my ViewModel Restaurant-Edit
has a collection of Menu
while Menu-Edit
has an instance of Restaurant
in its code.
namespace RestaurantProjet3.Models
{
public class MenuEditee
{
public int IdMenu { get; set; }
public int fk_Resto { get; set; }
public string NomPlat { get; set; }
public int Prix { get; set; }
public string Description { get; set; }
public string Categories { get; set; }
public byte?[] Photos { get; set; }
public virtual Restaurant Restaurant { get; set; }
}
}
Here, the problem that arises is the following, I worked on the page of edition of the menus of my restaurants whose here is the code
[HttpPost]
public ActionResult Edit_Menu(MenuEditee menuEdit)
{
if(!ModelState.IsValid)
{
return View(menuEdit);
}
Menu menuBd = contexteEF.Menu.Single(m => m.IdMenu == menuEdit.IdMenu);
menuBd = AutoMapper.Mapper.Map<MenuEditee,Menu>(menuEdit,menuBd);
contexteEF.SaveChanges();
return null;
When I want to replace the data contained in my comic by those contained in my ViewModel
, an exception occurs telling me that
"System.InvalidOperationException: Operation failed: unable to modify the relationship because one or all of the foreign key properties do not accept null values. When a modification is made to a relationship, a null value is assigned to the associated foreign key property. If the foreign key does not support null values, a new relationship must be defined, the non-null value must be assigned to the foreign key property or the unassociated object must be deleted"
and I noticed when I put a breakpoint in my code, the restaurant instance contained in my Menu-Edit
ViewModel returns a null value.
This is why when mapping its content in Menu
which is in my database, one of the attributes of Menu-Edit
is returned empty (the restaurant instance) which creates an exception.
What should i do to avoid errors and finally be able to persist my changes in the database?