Json circular reference and 'Children could not be evaluated' on Linq Include - asp.net-mvc

The following JsonResult returns:
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.IntegerList_76C57D0878505062AEA67E9EB9F708830FA20FDE4F13A53543EC2E6ED84C1A2C'
and according to the debugger
'Children could not be evaluated'
for the line
var integerLists = db.IntegerLists.Include("Integers");
If I remove the include, this runs successfully. Likewise if I execute the commented code instead.
In the past, I've solved circular references by decorating my domain models with [IgnoreDataMember] but that doesn't seem to be working this time.
Controller
public JsonResult GetIntegerLists()
{
var integerLists = db.IntegerLists.Include("Integers");
//var integerLists = new List<IntegerList>();
//integerLists.Add(new IntegerList()
//{
// IntegerListID = 1,
// Direction = "Ascending",
// Performance = 467,
// Integers = { new Integer { IntegerValue = 34 }, new Integer { IntegerValue = 5654 }, new Integer { IntegerValue = 343 } }
//});
//integerLists.Add(new IntegerList()
//{
// IntegerListID = 2,
// Direction = "Ascending",
// Performance = 637,
// Integers = { new Integer { IntegerValue = 4 }, new Integer { IntegerValue = 646 }, new Integer { IntegerValue = 23 } }
//});
//integerLists.Add(new IntegerList()
//{
// IntegerListID = 3,
// Direction = "Ascending",
// Performance = 235,
// Integers = { new Integer { IntegerValue = 64378 }, new Integer { IntegerValue = 1 }, new Integer { IntegerValue = 533 } }
//});
return Json(integerLists, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ActionResult Index(IntegerList viewModel)
{
if (ModelState.IsValid)
{
db.IntegerLists.Add(viewModel);
db.SaveChanges();
}
return View();
}
Models
public class Integer
{
public int IntegerID { get; set; }
public int IntegerValue { get; set; }
public int IntegerListID { get; set; }
public virtual IntegerList IntegerList { get; set; }
}
public class IntegerList
{
public int IntegerListID { get; set; }
public string Direction { get; set; }
public long Performance { get; set; }
public virtual ICollection<Integer> Integers { get; set; }
}

You have a navigation property back to the list it belongs to. You probably don't want to use that when serializing. Use the ScriptIgnore attribute.
public class Integer
{
public int IntegerID { get; set; }
public int IntegerValue { get; set; }
public int IntegerListID { get; set; }
[ScriptIgnore]
public virtual IntegerList IntegerList { get; set; }
}

Related

The Best overloaded method has some invalid arguments using Asp.net MVc

i am creating a simple invententy system in Asp.net Mvc i got the Error as
The best overloaded method match for 'System.Data.Entity.Dbset.Add(WebApplication27.Models.sale)' has some invalid arguments
i got the eror on this line of the project db.sales.Add(sale); i am tring to solve this problem since yesterday but couldn't do it.
sales.class file
**
public partial class sale
{
public int id { get; set; }
public Nullable<int> subtotal { get; set; }
public Nullable<int> pay { get; set; }
public Nullable<int> balance { get; set; }
}
}
**
Sales Controller
[HttpPost]
public ActionResult SaveNew(string data)
{
ajaxModel model = JsonConvert.DeserializeObject<ajaxModel>(data);
bool status = false;
try
{
using (aspposEntities1 db = new aspposEntities1())
{
//insert into Sales table
var sale = new sale
{
subtotal = model.total,
pay = model.pay,
balance = model.balance
};
db.sales.Add(sale);
**db.SaveChanges();** // Error this line
model.data.ForEach( m =>
{
//get the product and deduct the subtotal
int db_product = db.products.First(e => e.id== m.barcode_id);
db_product.qty = db_product.qty - m.qty;
db.sales_product.Add(new sales_product
{
// sales_id = sale.id,
barcode_id = m.barcode_id,
price = m.pro_price,
qty = m.qty,
total = m.total_cost
});
});
db.SaveChanges();
// model.orderid = sale.id;
status = true;
}
TempData["Data"] = model;
return new JsonResult { Data = new { status, message = "Entry saved successfully" } };
//return RedirectToAction("Print", model);
}
catch (Exception e)
{
return new JsonResult { Data = new { status, message = "There was an error saving the Entry" } };
}
}
tableView.cs
public class tableView
{
public string barcode_id { get; set; }
public string pname { get; set; }
public int pro_price { get; set; }
public int qty { get; set; }
public int total_cost { get; set; }
}
public class ajaxModel
{
public List<tableView> data { get; set; }
public int total { get; set; }
public int pay { get; set; }
public int balance { get; set; }
public string orderid { get; set; }
}
Can't leave comments so will have to leave this as an answer:
Your ID column doesn't look like it's being auto incremented, and you've not passed in an ID for it to use. You will either need to use:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
On the ID column to have it auto generate, or get the current highest id in the table and set it to that +1:
id = db.sales.Max(x=>x.id)+1

Database-First & Error: Unable to determine a valid ordering for dependent operations

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...

C# Creating Entity Object in one line

I have a Entity class
public class SiteMenu
{
public int MenuID { get; set; }
public string MenuName { get; set; }
public string NavURL { get; set; }
public int ParentMenuID { get; set; }
}
I want to create a collection of SiteMenu by the following code:
List<SiteMenu> all = new List<SiteMenu>();
To create and add an SiteMenu object to the List is this the correct format/syntax
all.Add(new SiteMenu(MenuID=1, MenuName="Test1", NavURL="http://test", ParentMenuID=0));
I like to use one line and keep adding to the list.
THanks.
You can use the collection initializer syntax to create the list and add the initial elements in one line:
var all = new List<SiteMenu> { new SiteMenu { MenuID = 1, MenuName = "Test1", NavURL = "http://test", ParentMenuID = 0} };
List<SiteMenu> list = new List<SiteMenu> {
all.Add(new SiteMenu(MenuID=1, MenuName="Test1", NavURL="http://test", ParentMenuID=0));
};
You should use a constructor.
public class SiteMenu
{
public int MenuID { get; set; }
public string MenuName { get; set; }
public string NavURL { get; set; }
public int ParentMenuID { get; set; }
public SiteMenu(int menuID, string menuName, string navURL, int parentMenuID) {
MenuID = menuID;
MenuName = menuName;
NavURL = navURL;
ParentMenuID = parentMenuID;
}
}
Then you can do:
List<SiteMenu> all = new List<SiteMenu>();
all.Add(new SiteMenu(1, "Test1", "http://test", 0));

Testing issues with MVC Controller using IOC

I am testing my controller code using IOC Unity. The issue is with the initialisation of the model that I am passing to constructor of my controller.
Here is my code in the test project
[TestMethod]
public void TestHomeControllerIndexMethod()
{
HomeController controller = new HomeController(new stubPeopleService());
ViewResult result = controller.Index() as ViewResult;
Assert.AreEqual(0, result);
}
Below is the code of the stubPeopleService that I have created which I pass to my controller constructor above
public class stubPeopleService : IPeople
{
public int Age
{
get;
set;
}
public string BirthPlace
{
get;
set;
}
public DateTime DateOfBirth
{
get;
set;
}
public int GetAge(DateTime reference, DateTime birthday)
{
int age = reference.Year - birthday.Year;
if (reference < birthday.AddYears(age)) age--;
return age + 1;
}
public int Height
{
get;
set;
}
public List<People> listPeople { get { return GetPeople(); } }
public string Name
{
get;
set;
}
public int Weight
{
get;
set;
}
private List<People> GetPeople()
{
List<People> list = new List<People>();
list.Add(new People
{
Name = "Ranjit Menon",
DateOfBirth = DateTime.Today,
BirthPlace = "London",
Age = 25,
Height = 175,
Weight = 85
});
return list.OrderBy(x => x.Name).ToList();
}
}
When I debug my test , I notice that the all the properties do not contain any value. The only property that contains value is listPeople property. The listpeople property does initialise the other properties but throws an object cannot be created error.Let me know if I am doing the test correctly. I need to do a test initialising the model with some values.
Code from my home controller
private IPeople peopleService;
public HomeController(IPeople people)
{
this.peopleService = people;
}
public ActionResult Index()
{
return View(peopleService);
}
Please find the IPeople interface below
public interface IPeople
{
int Age { get; set; }
string BirthPlace { get; set; }
DateTime DateOfBirth { get; set; }
int GetAge(DateTime reference, DateTime birthday);
int Height { get; set; }
List<People> listPeople { get; }
string Name { get; set; }
int Weight { get; set; }
}

Expression Func in Selector

I created two selector using Exp-Func I want to execute both in a single query. Code is as follows:
Expression<Func<Scholar, ScholarCultureWatchListView>> selector = z => new ScholarCultureWatchListView
{
ScholarId = z.ID,
Name = z.FirstName + " " + z.LastName
};
Expression<Func<Scholar, ScholarCultureWatchListView>> selector2 = z => new ScholarCultureWatchListView
{
Grade = z.CurrentGrade
};
var result= from s in db.Scholars
select new ScholarCultureWatchListView
{
**?????What is write here (selector, selector2)**
}
public class ScholarCultureWatchListView
{
public long ScholarId { get; set; }
public string Name { get; set; }
public Grade? Grade { get; set; }
public bool? HoldOverSkip { get; set; }
public Grade? GradeHoldOver { get; set; }
public bool? Iep { get; set; }
public int Tardies { get; set; }
public int Absences { get; set; }
public int YtdSuspensions { get; set; }
....
}
please solve my problem.
Thanks
If you want to get two separate instances of ScholarCultureWatchListView returned from a single call, you can do for example this (and you don't need selectors at all):
var result = from s in db.Scholars
select new[]
{
new ScholarCultureWatchListView
{
ScholarId = s.ID,
Name = s.FirstName + " " + z.LastName
},
new ScholarCultureWatchListView
{
Grade = z.CurrentGrade
},
};

Resources