I'm getting a "Cannot insert null into column" error from an unrelated table when trying to add a new record for the "original" table.
I have the following two (relevant) entities:
public class Complex
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public Guid OwnerId { get; set; }
[ForeignKey("OwnerId")]
public Owner Owner { get; set; }
public Guid AddressId { get; set; }
[ForeignKey("AddressId")]
public virtual Address Address { get; set; }
public virtual ICollection<Unit> Units { get; set; }
public virtual ICollection<StaffMember> StaffMembers { get; set; }
public Complex()
{
this.Id = System.Guid.NewGuid();
this.Units = new HashSet<Unit>();
this.StaffMembers = new HashSet<StaffMember>();
}
public void AddUnit(Unit unit)
{
Units.Add(unit);
}
public void AddStaff(StaffMember staffMember)
{
StaffMembers.Add(staffMember);
}
}
and
public class Owner
{
[Key]
public Guid Id { get; set; }
public string Name { get; set; }
public Guid ContactInfoId { get; set; }
[ForeignKey("ContactInfoId")]
public ContactInfo ContactInfo { get; set; }
public ICollection<StaffMember> Employees { get; set; }
public ICollection<Complex> Complexes { get; set; }
public Owner()
{
this.Id = System.Guid.NewGuid();
this.Employees = new HashSet<StaffMember>();
this.Complexes = new HashSet<Complex>();
}
public void AddEmployee(StaffMember employee)
{
Employees.Add(employee);
}
public void AddComplex(Complex complex)
{
Complexes.Add(complex);
}
}
I'm trying to add a new owner in the following code:
if (ModelState.IsValid)
{
Owner newOwner = new Owner();
ContactInfo newContactInfo = new ContactInfo();
Address newAddress = new Address();
newAddress.Address1 = viewModel.ContactInfo.Address.Address1;
newAddress.Address2 = viewModel.ContactInfo.Address.Address2;
newAddress.City = viewModel.ContactInfo.Address.City;
newAddress.State = viewModel.ContactInfo.Address.State;
newAddress.Zip = viewModel.ContactInfo.Address.Zip;
newContactInfo.Address = newAddress;
newContactInfo.Email = viewModel.ContactInfo.Email;
newContactInfo.Phone1 = viewModel.ContactInfo.Phone1;
newContactInfo.Phone2 = viewModel.ContactInfo.Phone2;
newOwner.Name = viewModel.Name;
newOwner.ContactInfo = newContactInfo;
using (REMSDAL dal = new REMSDAL())
{
dal.Owners.Add(newOwner);
var result = await dal.SaveChangesAsync();
if (result > 0)
{
viewModel.ActionStatusMessageViewModel.StatusMessage = "Owner " + viewModel.Name + " added.";
viewModel.Name = "";
return View(viewModel);
}
}
}
...but getting this error:
Exception Details: System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'OwnerId', table 'REMS.dbo.Complexes'; column does not allow nulls. UPDATE fails.
The statement has been terminated.
How can I be getting an error regarding Complexes when I'm trying to add an Owner?
I have a problem with the project I am working on. On POST:Edit, it saves my changes. On POST:Create, I receive this error: "Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values."
So I did what my teachers taught us in College: I just Googled it. The answers however were suggesting to change the ModelBuilder-fluent API. I do not think this would be inappropriate since I use Database-First approach (It says it is only for Code-First) AND my Save is functional in Edit. Since I wanted to work with ViewModels, I followed this tutorial. I even found and posted a solution for the tutorial about the Create method to help me with my problem. Please help me. I am about to throw my computer out of the window. Which is kind of complicated because they are made of tempered glass.
So here's the metadata for my model (with minimal data annotation for readability sake:
public partial class Employe
{
sealed class Metadata
{
[Key]
public int IdEmploye { get; set; }
public string NomEmploye { get; set; }
public string PrenomEmploye { get; set; }
[ForeignKey("TitreEmploye_IdTitre")]
public int IdTitre { get; set; }
[ForeignKey("Departement_IdDepartement")]
public int IdDepartement { get; set; }
[ForeignKey("Employe_IdSuperviseur")]
public int IdSuperviseur { get; set; }
public System.DateTime DateEmbauche { get; set; }
public Nullable<System.DateTime> DateDepart { get; set; }
public string StatutEmploye { get; set; }
[ForeignKey("Employeur_IdEmployeur")]
public int IdEmployeur { get; set; }
[ForeignKey("Localisation_IdLocalisation")]
public int IdLocalisation { get; set; }
public string Langue { get; set; }
public Nullable<bool> CarteAcces { get; set; }
[ForeignKey("TelephoneBureau_IdTelephoneBureau")]
public Nullable<int> IdTelephoneBureau { get; set; }
public Nullable<bool> CarteAffaire { get; set; }
public string AdresseCourriel { get; set; }
public bool CodeAlarme { get; set; }
public System.DateTime DateNaissance { get; set; }
public Nullable<bool> IsSuperviseur { get; set; }
public Nullable<bool> IsActif { get; set; }
}
}
}
Here's my problematic(?) model:
public partial class Employe
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Employe()
{
this.AccesApplicatif1 = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire1 = new HashSet<TelephoneCellulaire>();
this.CleBatiment1 = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite1 = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie1 = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();
}
public int IdEmploye { get; set; }
public string NomEmploye { get; set; }
public string PrenomEmploye { get; set; }
public int IdTitre { get; set; }
public int IdDepartement { get; set; }
public int IdSuperviseur { get; set; }
public System.DateTime DateEmbauche { get; set; }
public Nullable<System.DateTime> DateDepart { get; set; }
public string StatutEmploye { get; set; }
public int IdEmployeur { get; set; }
public int IdLocalisation { get; set; }
public string Langue { get; set; }
public Nullable<bool> CarteAcces { get; set; }
public Nullable<int> IdTelephoneBureau { get; set; }
public Nullable<bool> CarteAffaire { get; set; }
public string AdresseCourriel { get; set; }
public bool CodeAlarme { get; set; }
public System.DateTime DateNaissance { get; set; }
public Nullable<bool> IsSuperviseur { get; set; }
public Nullable<bool> IsActif { get; set; }
public virtual Departement Departement { get; set; }
public virtual Employeur Employeur { get; set; }
public virtual Localisation Localisation { get; set; }
public virtual TelephoneBureau TelephoneBureau { get; set; }
public virtual TitreEmploye TitreEmploye { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AccesApplicatif> AccesApplicatif1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<TelephoneCellulaire> TelephoneCellulaire1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CleBatiment> CleBatiment1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<EquipementInfo> EquipementInfo { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<GroupeSecurite> GroupeSecurite1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<VehiculeCompagnie> VehiculeCompagnie1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Employe> Employe1 { get; set; }
public virtual Employe Employe2 { get; set; }
public string NomSuperviseur
{
get
{
return string.Format("{0} {1}", PrenomEmploye, NomEmploye);
}
}
}
As I said, since I wanted to work with ViewModels, here's the culprit:
public partial class EmployeVM
{
public Employe Employe { get; set; } //Employe
public string NomEmploye { get; set; } //Employe
public string PrenomEmploye { get; set; } //Employe
public DateTime DateNaissance { get; set; } //Employe
public string Langue { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<Titre> Titres { get; set; } //TitreEmploye
public class Titre
{
public string description { get; set; } //TitreEmploye
}
//////////////////////////////////////////////////////////////
public IEnumerable<Departement> Departements { get; set; } //Departement
public class Departement
{
public string description { get; set; } //Departement
}
//////////////////////////////////////////////////////////////
public IEnumerable<Superviseur> Superviseurs { get; set; } //Employe
public class Superviseur
{
public string nomSuperviseur { get; set; } //Employe
}
public string StatutEmploye { get; set; } //Employe
public DateTime DateEmbauche { get; set; } //Employe
public Nullable<System.DateTime> DateDepart { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<Employeur> Employeurs { get; set; } //Employeur
public class Employeur
{
public string nomEmployeur { get; set; } //Employeur
}
//////////////////////////////////////////////////////////////
public IEnumerable<Localisation> Localisations { get; set; } //Localisation
public class Localisation
{
public string description { get; set; } //Localisation
}
public bool CarteAcces { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<TelephoneBureau> TelephoneBureaux { get; set; } //TelephoneBureau
public class TelephoneBureau
{
public string extension { get; set; } //TelephoneBureau
}
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllTelephoneCellulaires { get; set; } //TelephoneCellulaire
private List<int> _selectedTelephoneCellulaires;
public List<int> SelectedTelephoneCellulaires
{
get
{
if (_selectedTelephoneCellulaires == null)
{
_selectedTelephoneCellulaires = Employe.TelephoneCellulaire1.Select(m => m.IdTelephoneCellulaire).ToList();
}
return _selectedTelephoneCellulaires;
}
set { _selectedTelephoneCellulaires = value; }
}
public bool CarteAffaire { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllEquipementInformatiques { get; set; } //EquipementInfo
private List<int> _selectedEquipementInformatiques;
public List<int> SelectedEquipementInformatiques
{
get
{
if (_selectedEquipementInformatiques == null)
{
_selectedEquipementInformatiques = Employe.EquipementInfo.Select(m => m.IdEquipementInfo).ToList();
}
return _selectedEquipementInformatiques;
}
set { _selectedEquipementInformatiques = value; }
}
public string AdresseCourriel { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllGroupeSecurites { get; set; } //GroupeSecurite
private List<int> _selectedGroupeSecurites;
public List<int> SelectedGroupeSecurites
{
get
{
if (_selectedGroupeSecurites == null)
{
_selectedGroupeSecurites = Employe.GroupeSecurite1.Select(m => m.IdGroupeSecurite).ToList();
}
return _selectedGroupeSecurites;
}
set { _selectedGroupeSecurites = value; }
}
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllAccesApplicatifs { get; set; } //AccesApplicatif
private List<int> _selectedAccesApplicatifs;
public List<int> SelectedAccesApplicatifs
{
get
{
if (_selectedAccesApplicatifs == null)
{
_selectedAccesApplicatifs = Employe.AccesApplicatif1.Select(m => m.IdAccesApplicatif).ToList();
}
return _selectedAccesApplicatifs;
}
set { _selectedAccesApplicatifs = value; }
}
public bool CodeAlarme { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllCleBatiments { get; set; } //CleBatiment
private List<int> _selectedCleBatiments;
public List<int> SelectedCleBatiments
{
get
{
if (_selectedCleBatiments == null)
{
_selectedCleBatiments = Employe.CleBatiment1.Select(m => m.IdCleBatiment).ToList();
}
return _selectedCleBatiments;
}
set { _selectedCleBatiments = value; }
}
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllVehiculeCompagnies { get; set; } //VehiculeCompagnie
private List<int> _selectedVehiculeCompagnies;
public List<int> SelectedVehiculeCompagnies
{
get
{
if (_selectedVehiculeCompagnies == null)
{
_selectedVehiculeCompagnies = Employe.VehiculeCompagnie1.Select(m => m.IdVehiculeCompagnie).ToList();
}
return _selectedVehiculeCompagnies;
}
set { _selectedVehiculeCompagnies = value; }
}
public bool IsSuperviseur { get; set; } //Employe
public bool IsActif { get; set; } //Employe
public EmployeVM()
{
AllTelephoneCellulaires = new List<SelectListItem>();
AllEquipementInformatiques = new List<SelectListItem>();
AllGroupeSecurites = new List<SelectListItem>();
AllAccesApplicatifs = new List<SelectListItem>();
AllCleBatiments = new List<SelectListItem>();
AllVehiculeCompagnies = new List<SelectListItem>();
}
}
And here's the Create part of my Controller (I KNOW I will have to add some methods to comply to DRY, but for now, that's what it is:
// GET: Employes/Create
//[AcceptVerbs(HttpVerbs.Get), ImportModelStateFromTempData]
public ActionResult Create()
{
var employeView = new EmployeVM();
//Population pour les ListBoxFor
var allTelephoneCellulaireActifList = db.TelephoneCellulaireActif.ToList();
ViewBag.AllTelephoneCellulaires = allTelephoneCellulaireActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdTelephoneCellulaire.ToString()
});
var allEquipementInfoActifList = db.EquipementInfoActif.ToList();
ViewBag.AllEquipementInformatiques = allEquipementInfoActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdEquipementInfo.ToString()
});
var allGroupeSecuriteList = db.GroupeSecurite.ToList();
ViewBag.AllGroupeSecurites = allGroupeSecuriteList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdGroupeSecurite.ToString()
});
var allAccesApplicatifActifList = db.AccesApplicatifActif.ToList();
ViewBag.AllAccesApplicatifs = allAccesApplicatifActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdAccesApplicatif.ToString()
});
var allCleBatimentList = db.CleBatiment.ToList();
ViewBag.AllCleBatiments = allCleBatimentList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdCleBatiment.ToString()
});
var allVehiculeCompagnieActifList = db.VehiculeCompagnieActif.ToList();
ViewBag.AllVehiculeCompagnies = allVehiculeCompagnieActifList.Select(o => new SelectListItem
{
Text = o.DescriptionVehicule,
Value = o.IdVehiculeCompagnie.ToString()
});
//Zero-or-One-to-Many relationships
List<TitreEmployeActif> ListeTitreEmployeActif = db.TitreEmployeActif.OrderBy(titre => titre.Description).ToList();
ViewBag.IdTitre = new SelectList(ListeTitreEmployeActif, "IdTitre", "Description");
List<Departement> ListeDepartement = db.Departement.OrderBy(departement => departement.Description).ToList();
ViewBag.IdDepartement = new SelectList(ListeDepartement, "IdDepartement", "Description");
List<EmployeSuperviseurActif> ListeEmployeSuperviseurActif = db.EmployeSuperviseurActif.OrderBy(sup => sup.PrenomNom).ToList();
ViewBag.IdSuperviseur = new SelectList(ListeEmployeSuperviseurActif, "IdEmploye", "PrenomNom");
List<Employeur> ListeEmployeur = db.Employeur.OrderBy(employeur => employeur.NomEmployeur).ToList();
ViewBag.IdEmployeur = new SelectList(ListeEmployeur, "IdEmployeur", "NomEmployeur");
List<Localisation> ListeLocalisation = db.Localisation.OrderBy(localisation => localisation.Description).ToList();
ViewBag.IdLocalisation = new SelectList(ListeLocalisation, "IdLocalisation", "Description");
List<TelephoneBureauActif> ListeTelephoneBureauActif = db.TelephoneBureauActif.OrderBy(phone => phone.Extension).ToList();
ViewBag.IdTelephoneBureau = new SelectList(ListeTelephoneBureauActif, "IdTelephoneBureau", "Extension");
return View();
}
// POST: Employes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to,
// for more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EmployeVM employeView)
{
if (!ModelState.IsValid)
{
foreach (var obj in ModelState.Values)
{
foreach (var error in obj.Errors)
{
if (!string.IsNullOrEmpty(error.ErrorMessage))
System.Diagnostics.Debug.WriteLine("ERROR WHY = " + error.ErrorMessage);
}
}
}
if (ModelState.IsValid)
{
var employeToAdd = db.Employe
.Include(e => e.TelephoneCellulaire1)
.Include(e => e.EquipementInfo)
.Include(e => e.GroupeSecurite1)
.Include(e => e.AccesApplicatif1)
.Include(e => e.CleBatiment1)
.Include(e => e.VehiculeCompagnie1)
.First();
if (TryUpdateModel(employeToAdd, "Employe", new string[] { "IdEmploye", "NomEmploye", "PrenomEmploye", "IdTitre", "IdDepartement", "IdSuperviseur", "DateEmbauche", "DateDepart", "StatutEmploye", "IdEmployeur", "IdLocalisation", "Langue", "CarteAcces", "TelephoneCellulaire", "IdTelephoneBureau", "CarteAffaire", "EquipementInformatique", "AdresseCourriel", "GroupeSecurite", "AccesApplicatif", "CodeAlarme", "CleBatiment", "VehiculeCompagnie", "DateNaissance", "IsSuperviseur", "IsActif" }))
{
var updatedTelephoneCellulaires = new HashSet<int>(employeView.SelectedTelephoneCellulaires);
var updatedEquipementInformatiques = new HashSet<int>(employeView.SelectedEquipementInformatiques);
var updatedGroupeSecurites = new HashSet<int>(employeView.SelectedGroupeSecurites);
var updatedAccesApplicatifs = new HashSet<int>(employeView.SelectedAccesApplicatifs);
var updatedCleBatiments = new HashSet<int>(employeView.SelectedCleBatiments);
var updatedVehiculeCompagnies = new HashSet<int>(employeView.SelectedVehiculeCompagnies);
//Prochaine ligne db.TelephoneCellulaire1 !!! ou db.TelephoneCellulaireActif ??? Check readonly
foreach (TelephoneCellulaire telephone in db.TelephoneCellulaire)
{
if (!updatedTelephoneCellulaires.Contains(telephone.IdTelephoneCellulaire))
{
employeToAdd.TelephoneCellulaire1.Remove(telephone);
}
else
{
employeToAdd.TelephoneCellulaire1.Add(telephone);
}
}
foreach (EquipementInfo equipement in db.EquipementInfo)
{
if (!updatedEquipementInformatiques.Contains(equipement.IdEquipementInfo))
{
employeToAdd.EquipementInfo.Remove(equipement);
}
else
{
employeToAdd.EquipementInfo.Add(equipement);
}
}
foreach (GroupeSecurite groupe in db.GroupeSecurite)
{
if (!updatedGroupeSecurites.Contains(groupe.IdGroupeSecurite))
{
employeToAdd.GroupeSecurite1.Remove(groupe);
}
else
{
employeToAdd.GroupeSecurite1.Add(groupe);
}
}
foreach (AccesApplicatif acces in db.AccesApplicatif)
{
if (!updatedAccesApplicatifs.Contains(acces.IdAccesApplicatif))
{
employeToAdd.AccesApplicatif1.Remove(acces);
}
else
{
employeToAdd.AccesApplicatif1.Add(acces);
}
}
foreach (CleBatiment cle in db.CleBatiment)
{
if (!updatedCleBatiments.Contains(cle.IdCleBatiment))
{
employeToAdd.CleBatiment1.Remove(cle);
}
else
{
employeToAdd.CleBatiment1.Add(cle);
}
}
foreach (VehiculeCompagnie vehicule in db.VehiculeCompagnie)
{
if (!updatedVehiculeCompagnies.Contains(vehicule.IdVehiculeCompagnie))
{
employeToAdd.VehiculeCompagnie1.Remove(vehicule);
}
else
{
employeToAdd.VehiculeCompagnie1.Add(vehicule);
}
}
}
db.Employe.Add(employeToAdd);
db.SaveChanges();
return RedirectToAction("Index");
}
var allTelephoneCellulaireActifList = db.TelephoneCellulaireActif.ToList();
ViewBag.AllTelephoneCellulaires = allTelephoneCellulaireActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdTelephoneCellulaire.ToString()
});
var allEquipementInfoActifList = db.EquipementInfoActif.ToList();
ViewBag.AllEquipementInformatiques = allEquipementInfoActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdEquipementInfo.ToString()
});
var allGroupeSecuriteList = db.GroupeSecurite.ToList();
ViewBag.AllGroupeSecurites = allGroupeSecuriteList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdGroupeSecurite.ToString()
});
var allAccesApplicatifActifList = db.AccesApplicatifActif.ToList();
ViewBag.AllAccesApplicatifs = allAccesApplicatifActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdAccesApplicatif.ToString()
});
var allCleBatimentList = db.CleBatiment.ToList();
ViewBag.AllCleBatiments = allCleBatimentList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdCleBatiment.ToString()
});
var allVehiculeCompagnieActifList = db.VehiculeCompagnieActif.ToList();
ViewBag.AllVehiculeCompagnies = allVehiculeCompagnieActifList.Select(o => new SelectListItem
{
Text = o.DescriptionVehicule,
Value = o.IdVehiculeCompagnie.ToString()
});
//Zero-or-One-to-Many relationships
List<TitreEmployeActif> ListeTitreEmployeActif = db.TitreEmployeActif.OrderBy(titre => titre.Description).ToList();
ViewBag.IdTitre = new SelectList(ListeTitreEmployeActif, "IdTitre", "Description");
List<Departement> ListeDepartement = db.Departement.OrderBy(departement => departement.Description).ToList();
ViewBag.IdDepartement = new SelectList(ListeDepartement, "IdDepartement", "Description");
List<EmployeSuperviseurActif> ListeEmployeSuperviseurActif = db.EmployeSuperviseurActif.OrderBy(sup => sup.PrenomNom).ToList();
ViewBag.IdSuperviseur = new SelectList(ListeEmployeSuperviseurActif, "IdEmploye", "PrenomNom");
List<Employeur> ListeEmployeur = db.Employeur.OrderBy(employeur => employeur.NomEmployeur).ToList();
ViewBag.IdEmployeur = new SelectList(ListeEmployeur, "IdEmployeur", "NomEmployeur");
List<Localisation> ListeLocalisation = db.Localisation.OrderBy(localisation => localisation.Description).ToList();
ViewBag.IdLocalisation = new SelectList(ListeLocalisation, "IdLocalisation", "Description");
List<TelephoneBureauActif> ListeTelephoneBureauActif = db.TelephoneBureauActif.OrderBy(phone => phone.Extension).ToList();
ViewBag.IdTelephoneBureau = new SelectList(ListeTelephoneBureauActif, "IdTelephoneBureau", "Extension");
return View(employeView);
}
And just to complete the picture, an extract from Create.cshtml:
<div class="form-group">
#Html.LabelFor(model => model.AllEquipementInformatiques, "Équipements informatiques", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBoxFor(model => model.SelectedEquipementInformatiques, (IEnumerable<SelectListItem>)ViewBag.AllEquipementInformatiques, new { #class = "form-control" })
</div>
</div>
Speaking about a picture, here's a little capture of one of my Many-to-Many table, with data entered with Edit:
Employe_VehiculeCompagnie
The thing to know (and I think it might be part of the problem) is: all of the 6 Many-To-Many relationships are optional. But even when I try to create a new Employe with at least one item in each of the 6 Many-to-Many field, it throws that error. And it still works in Edit. Questions: why this error is thrown and how can I make my app works? Any help would be greatly appreciated.
Edit:
Should I add this? One of my join table:
CREATE TABLE [dbo].[Employe_GroupeSecurite] (
[IdEmploye] INT NOT NULL,
[IdGroupeSecurite] INT NOT NULL,
PRIMARY KEY CLUSTERED ([IdEmploye] ASC, [IdGroupeSecurite] ASC),
CONSTRAINT [FK_Employe_GroupeSecurite_Employe] FOREIGN KEY ([IdEmploye]) REFERENCES [dbo].[Employe] ([IdEmploye]),
CONSTRAINT [FK_Employe_GroupeSecurite_GroupeSecurite] FOREIGN KEY ([IdGroupeSecurite]) REFERENCES [dbo].[GroupeSecurite] ([IdGroupeSecurite])
Now what?
I found it! Here's my solution, in case someone else tumbles with the same problem.
For some strange reason, Visual Studio added a '1' at the end of some of my Many-to-Many tables name. Entity Framework did not like it (neither did I), so I renamed them in my model:
Example:
public Employe()
{
this.AccesApplicatif1 = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire1 = new HashSet<TelephoneCellulaire>();
this.CleBatiment1 = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite1 = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie1 = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();
}
Became:
this.AccesApplicatif = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire = new HashSet<TelephoneCellulaire>();
this.CleBatiment = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();
Visual Studio was intelligent enough to rename them in pretty much everything, except in my Entities.edmx, Views and my Metadata. I took great care of it and now, verything work like a charm. I still don't understand why I was able to Edit my employes though...
Fetch data from database some error occur here (AdminPurpose con = i.a ) Message show Cannot implicitly converted type.Please see below for my code snippets:
public JsonResult GetInfor()
{
List<AdminPurpose> all = new List<AdminPurpose>();;
using (db_Hajj_UmrahEntities dc= new db_Hajj_UmrahEntities()) {
var datas = (from a in dc.Duas join b in dc.Purposes on a.PurposeId equals b.Id
select new {
a,
b.PurPose1
});
if(datas != null) {
foreach (var i in datas)
{
AdminPurpose con = i.a ;
con.PurPose1 = i.PurPose1;
all.Add(con);
}
}
}
return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Model class one to many relation here it's using
[MetadataType(typeof(DuaMetaData))]
public partial class AdminPurpose
{
public string PurPose1 { get; set; }
}
public class DuaMetaData
{
public string Dua_Name { get; set; }
public string Arabic_Word { get; set; }
public string Translation_English { get; set; }
public string Source { get; set; }
[Display(Name = "Purpose")]
public int PurposeId { get; set; }
}
When I try update database the property Childrens not saving but SortOrder
and display name are success.
This is my model:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Int64 Id { get; set; }
public Int64? LanguageId { get; set; }
[ForeignKey("LanguageId")]
public Language Language { get; set; }
public int SortOrder { get; set; }
public string DisplayName { get; set; }
[ForeignKey("Childrens")]
public Int64? ParentId { get; set; }
public ICollection<Menu> Childrens { get; set; }
I called this function with new parameters:
public void SaveMenu(List<Menu> newMenu)
{
foreach(Menu _addMenu in newMenu)
{
this.Update(_addMenu);
}
this.Commit();
}
public void Update(T entity)
{
try
{
DbEntityEntry _dbEntityEntry = this.DbContext.Entry(entity);
DbContext.Entry(entity).State = EntityState.Modified;
if (_dbEntityEntry.State == EntityState.Detached)
this.dbSet.Attach(entity);
_dbEntityEntry.State = EntityState.Modified;
}
}
public bool Commit()
{
try
{
this.DbContext.SaveChanges();
}
catch (Exception ex)
{
return false;
}
return true;
}
And the childrens are not change but sortOrder success to change.
Why is it happening?
EDIT:
I found solution the problem because the children objects are dummy and need to get the "real" object from the DB
public void SaveMenu(List<Menu> newMenu)
{
foreach(Menu _addMenu in newMenu)
{
List<Menu> listMenu = new List<Menu>();
foreach (Menu child in _addMenu.Childrens)
{
Menu _menuFromDB = this.Query().FirstOrDefault(s => s.Id == child.Id);
_menuFromDB.SortOrder = child.SortOrder;
listMenu.Add(_menuFromDB);
}
_addMenu.Childrens = listMenu;
this.Update(_addMenu,null);
}
this.Commit();
}
I'm newbie to MVC architecture.When I'm trying to update, its showing error ,Its totally strange but the data is updating.
The model item passed into the dictionary is of type 'CMS.Domain.Models.Site', but this dictionary requires a model item of type 'CMS.Web.ViewModels.SiteModel'.'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: The model item passed into the dictionary is of type 'CMS.Web.ViewModels.SiteModel', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[CMS.Web.ViewModels.SiteModel]'.
My code looks like:
ViewModels:
namespace CMS.Web.ViewModels
{
public class SiteModel
{
public SiteModel()
{
SiteStatus = new List<SelectListItem>();
}
[Key]
public int ID { get; set; }
[Required(ErrorMessage = "Site Name is required")]
[Display(Name = "Site Name")]
public string Title { get; set; }
[Display(Name = "Require Login")]
public bool RequiresLogin { get; set; }
[Display(Name = "Force HTTPS")]
public bool ForceHTTPS { get; set; }
[Display(Name = "Enable Approval")]
public bool Approval { get; set; }
[AllowHtml]
public IList<SelectListItem> SiteStatus { get; set; }
public bool Deleted { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedOn
{
get { return _createdOn; }
set { _createdOn = value; }
}
private DateTime _createdOn = DateTime.Now;
public string LastUpdatedBy { get; set; }
public DateTime LastUpdatedOn
{
get { return _lastUpdatedOn; }
set { _lastUpdatedOn = value; }
}
private DateTime _lastUpdatedOn = DateTime.Now;
[Display(Name = "Site State")]
public string SiteState { get; set; }
}
}
Model:
namespace CMS.Domain.Models
{
public partial class Site : Model
{
public string Title { get; set; }
public bool Approval { get; set; }
public bool RequiresLogin { get; set; }
public bool ForceHTTPS { get; set; }
public virtual string SiteStatus { get; set; }
public bool Deleted { get; set; }
}
}
Controller:
public ActionResult Index()
{
var _sites = _siterepository.FindAll();
return View(_sites);
}
public ActionResult Add()
{
var model = new SiteModel();
var _SiteStatus = _siterepository.GetSiteStatus();
foreach (var _sitestatus in _SiteStatus)
{
model.SiteStatus.Add(new SelectListItem()
{
Text = _sitestatus.StatusName,
Value = _sitestatus.StatusName.ToString()
});
}
return View(model);
}
[HttpPost]
public ActionResult Add(SiteModel _sitemodel)
{
var model = _sitemodel.ToEntity();
_siterepository.Add(model);
return View(model);
}
public ActionResult Edit(int id)
{
var model = new SiteModel();
var Site = _siterepository.Find(id);
model = Site.ToModel();
var _SiteStatus = _siterepository.GetSiteStatus();
foreach (var _sitestatus in _SiteStatus)
{
model.SiteStatus.Add(new SelectListItem()
{
Text = _sitestatus.StatusName,
Value = _sitestatus.StatusName.ToString(),
Selected = _sitestatus.StatusName == Site.SiteStatus
});
}
return View(model);
}
[HttpPost]
public ActionResult Edit(SiteModel _sitemodel)
{
var model = _sitemodel.ToEntity();
_siterepository.Update(model);
return View(model);
}
I'm struggling to resolve this , please help.
Check your View's model declaration. It is expecting an enumerable list (IEnumerable<CMS.Web.ViewModels.SiteModel>), but you are passing it a single instance of CMS.Web.ViewModels.SiteModel