Expression Func in Selector - asp.net-mvc

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

Related

Cannot insert the value NULL into column from unrelated entity

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?

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

How create view for show cookie's info in asp.net mvc using razor?

I'm developing an online store using asp.net mvc 5 and I used cookie for add goods to cart . I want to have a page to show selected items (in cookie) and I don't know how do it, I just wrote an action result for it named Basket . I should use #model List<BasketVM> in my view but when don't know how ?!
could anyone help me please ?
Thanks
GoodController
[HttpGet]
public ActionResult Basket()
{
GoodDetailsRepositories blGoodDetails = new GoodDetailsRepositories();
List<BasketVM> listBasket = new List<BasketVM>();
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = Request.Cookies.Count - 1; i >= 0; i--)
{
if (lst.Where(p => p.Name == Request.Cookies[i].Name).Any() == false)
lst.Add(Request.Cookies[i]);
}
foreach (var item in lst.Where(p => p.Name.StartsWith("NishtmanCart_")))
{
listBasket.Add(new BasketVM {
GoodDetails = blGoodDetails.Find(Convert.ToInt32(item.Name.Substring(13))), Count =Convert.ToInt32(item.Value) });
}
return View(listBasket);
}
BasketVM.cs
public class BasketVM
{
public NP1.Models.GoodDetail GoodDetails { get; set; }
public int Count { get; set; }
}
GoodDetails.cs
public partial class GoodDetail
{
public GoodDetail()
{
this.FactorItems = new HashSet<FactorItem>();
}
public int DetailsGoodID { get; set; }
public int FKSubGoods { get; set; }
public string NishtmanCode { get; set; }
public string DetailsColor { get; set; }
public string DetailsExist { get; set; }
public long DetailsNowPrice { get; set; }
public Nullable<long> DetailsPrePrice { get; set; }
public string DetailsName { get; set; }
public string DetailsLeatherType { get; set; }
public string DetailsWeight { get; set; }
public string DetailsSize { get; set; }
public string DetailsProducer { get; set; }
public string DetailsExtraInfo { get; set; }
public string DetailsURL { get; set; }
public string DetailsKeyWords { get; set; }
public string DetailsTags { get; set; }
public int DetailsLike { get; set; }
public int DetailsDisLike { get; set; }
public string DetailsImage1 { get; set; }
public string DetailsSmallImage1 { get; set; }
public string DetailsImage2 { get; set; }
public string DetailsSmallImage2 { get; set; }
public string DetailsImage3 { get; set; }
public string DetailsSmallImage3 { get; set; }
public string DetailsImage4 { get; set; }
public string DetailsSmallImage4 { get; set; }
public virtual SubGood SubGood { get; set; }
public virtual ICollection<FactorItem> FactorItems { get; set; }
}
Add to cart code
public ActionResult AddToCart (int Id , int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//Edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//Add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,
Html = "cart items (" + CartCount.ToString() + ")"
}
);
}
catch(Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = "alert('Good didn't add');",
Html = ""
}
);
}
}
with what name you are saving the cookies you can retrieve like this let say userid u want to get rest what you have wriiten will work:
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Userid"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Userid"];
// retrieve cookie data here
}
how to call in view :
Viewbag.userid = #Request.Cookies["Userid"].value
In order to read a cookie client-side it needs to be created with the HttpOnly flag set to false.
Please go thorugh the below already asked question.
MVC Access stored cookie

Model value not accessable

I have a model which holds some details about an account (Name, Id etc) and then it has a type called Transaction, which holds information about the currently selected account transaction. A transaction can then have many transaction lines. So I have a List<TransactionsLine> property.
I am trying to set the value of a Drop down list, using the model, the value being in the List<> property. At the moment, there can, and must, only be one item in the list.
#Html.DropDownListFor(x=>x.Transaction.TransactionLines[0].CategoryId, Model.TransactionReferences.Categories, new {#onchange="populateSubCategory()"})
However, when I run this, the list defaults to the first item in the list.
In debug mode, when I hover the mouse over x.Transaction.TransactionLines[0].CategoryId, it doesn't show me a value. But when hover over the collection, Model.TransactionReferences.Categories, I see it has a valid list. It just won't set the selected value.
Am I doing this wrong?
It works in other drop downs I use, BUT the select value is in the top most level of my model:
#Html.DropDownListFor(x => x.Transaction.ThirdPartyId, Model.TransactionReferences.ThirdParties, new { #class = "cmbThirdParty form-control", #onchange = "populateDefaults()" })
That one works fine.
Note, doing it manually, works:
<select class="form-control" id="cmbCategory" onchange="populateSubCategory()">
<option value="0">Select a One</option>
#foreach (var cat in Model.TransactionReferences.Categories)
{
//var selected = cat.Value == Model.Transaction.TransactionLines[0].CategoryId.ToString() ? "selected" : "";
<option value="#cat.Value">#cat.Text</option>
}
</select>
But doesn't feel like the best way to do it.
Model:
The main model passed to the view:
public class TransactionModel
{
public int BankAccountId { get; set; }
public string BankAccountName { get; set; }
public TransactionContainer Transaction { get; set; }
public TransactionReferenceModel TransactionReferences { get; set; }
public DateTime DefaultDate { get; set; }
}
The TransactionReferenceModel holds all my 'reference' data used to populate drop down lists:
public class TransactionReferenceModel
{
public List<SelectListItem> TransactionTypes { get; set; }
public List<SelectListItem> EntryTypes { get; set; }
public List<SelectListItem> SubCategories { get; set; }
public List<SelectListItem> Categories { get; set; }
public List<SelectListItem> ThirdParties { get; set; }
public List<SelectListItem> CostCentres { get; set; }
}
The TransactionContainer model holds allthe main details about the selected transaction:
public class TransactionContainer
{
public int Id { get; set; }
public int AccountId { get; set; }
public int TransactionTypeId { get; set; }
public string TransactionType { get; set; }
public int EntryTypeId { get; set; }
public string EntryType { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/dd/yyyy}")]
public DateTime TransactionDate { get; set; }
public string ThirdParty { get; set; }
public int ThirdPartyId { get; set; }
public string Account { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "C2")]
public decimal Amount { get; set; }
public string Notes { get; set; }
public string CategoryDisplay { get; set; }
public string CostCentreDisplay { get; set; }
public decimal RunningBalance { get; set; }
public List<TransactionLine> TransactionLines { get; set; }
}
That then holds a list of transaction lines that make up the transaction. The transaction line holds the property I am trying to set the drop down to, which is CategoryId:
public class TransactionLine
{
public int Id { get; set; }
public int TransactionId { get; set; }
public int? CostCentreId { get; set; }
public string CostCentre { get; set; }
public int SubCategoryId { get; set; }
public string SubCategory { get; set; }
public int CategoryId { get; set; }
public string Category { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "C2")]
public decimal Amount { get; set; }
public string Notes { get; set; }
}
And here is how I am populating my model and sending it to the view:
public ActionResult EditTransaction(int? transactionId, int? bankAccountId)
{
// Create the main view object
var model = new TransactionModel
{
Transaction = new TransactionContainer
{
TransactionLines = new List<TransactionLine>()
}
};
if (transactionId != null) // This is an Edit, as opposed to an Add
{
var item = new TransactionService(currentUserId).GetTransaction(transactionId.Value);
// Populate the Reference object used to populate drop downs.
model.TransactionReferences = PopulateReferenceDate(model.TransactionReferences, item.TransactionLines[0].SubCategoryId);
model.BankAccountId = item.AccountId;
model.BankAccountName = item.Account.FullName;
model.DefaultDate = Session["DefaultDate"] != null
? DateTime.Parse(Session["DefaultDate"].ToString())
: DateTime.UtcNow;
model.Transaction.AccountId = item.AccountId;
model.Transaction.Amount = item.Amount;
model.Transaction.TransactionLines.Add(new TransactionLine
{
Id = item.TransactionLines[0].Id,
CategoryId = item.TransactionLines[0].SubCategory.CategoryId,
CostCentreId = item.TransactionLines[0].CostCentreId,
Notes = item.TransactionLines[0].Notes,
Amount = item.TransactionLines[0].Amount,
SubCategoryId = item.TransactionLines[0].SubCategoryId,
TransactionId = model.Transaction.Id
});
model.Transaction.EntryTypeId = item.EntryTypeId;
model.Transaction.Id = transactionId.Value;
model.Transaction.Notes = item.Notes;
model.Transaction.ThirdPartyId = item.ThirdPartyId;
model.Transaction.TransactionDate = item.TransactionDate;
model.Transaction.TransactionTypeId = item.TransactionTypeId;
}
else
{
// Populate the bank account details
var bank = new BankAccountService(currentUserId).GetBankAccountById(bankAccountId.Value);
model.TransactionReferences = PopulateReferenceDate(model.TransactionReferences, null);
model.BankAccountId = bank.Id;
model.BankAccountName = bank.FullName;
model.Transaction.TransactionLines.Add(new TransactionLine
{
TransactionId = model.Transaction.Id // Link the transaction line to the transaction.
});
var transactionDate = Session["DefaultDate"] != null
? DateTime.Parse(Session["DefaultDate"].ToString())
: DateTime.UtcNow;
// Populate the object to hold the Transaction data, so that we can use it and return it in the view.
model.Transaction.TransactionDate = transactionDate;
}
return View(model);
}
I think you should use the SelectList Constructor in your view, in order to indicate the default value, like this:
#Html.DropDownListFor(
x => x.Transaction.TransactionsLines[0].CategoryId,
new SelectList(Model.TransactionReferences.Categories, "Value", "Text", Model.Transaction.TransactionsLines[0].CategoryId)
)
You are not restricted to use List< SelectListItem > for the collections. You can use a List of a specific class also.
This is the Controller Action Method code:
public class HomeController : Controller
{
public ActionResult Index()
{
var m = new AccountModel();
m.Transaction = new Transaction();
m.Transaction.TransactionsLines = new List<TransactionsLine>();
m.Transaction.TransactionsLines.Add(new TransactionsLine() { CategoryId = 2 });
m.TransactionReferences = new TransactionReferences();
m.TransactionReferences.Categories = new List<SelectListItem>()
{ new SelectListItem() { Text = "Cat1", Value = "1" },
new SelectListItem() { Text = "Cat2", Value = "2" },
new SelectListItem() { Text = "Cat3", Value = "3" }
};
return View(m);
}
}

How to use (left/right) outer join for this LINQ that join 3 entities?

Using MVC 3, EF4.1:
Building a quiz screen, I am joining three entities: Steps, Questions, Responses
Each Step can have many questions, each question can have one or no responses
My issue is when I have no answers in my query, it returns steps with no questions. How do I incorporate an outer join (left/right) into this LINQ?
var steps = from s in db.Steps
join r in db.Responses.Where(x => x.ReviewID == id)
on s.StepID equals r.Question.StepID into g
orderby s.StepOrder
select new Quiz
{
StepID = s.StepID,
Title = s.Title,
Results = from x in g
orderby x.Question.DisplayOrder
select new Result
{
QuestionID = x.Question.QuestionID,
DisplayOrder = x.Question.DisplayOrder,
Choices = x.Question.Choices,
ControlType = x.Question.ControlType,
QuestionText = x.Question.QuestionText,
AnswerValue = x.AnswerValue
}
};
Question Model:
public class Question
{
public Question()
{
this.Responses = new List<Response>();
}
public int QuestionID { get; set; }
public string QuestionText { get; set; }
public Nullable<bool> Required { get; set; }
public int DisplayOrder { get; set; }
public int StepID { get; set; }
public Nullable<int> DataType { get; set; }
public Nullable<int> ControlType { get; set; }
public string Choices { get; set; }
public Nullable<int> MaxLength { get; set; }
public virtual ICollection<Response> Responses { get; set; }
public virtual Step Step { get; set; }
public string NumberedQuestion
{
get { return String.Format("{0}. {1}", DisplayOrder, QuestionText); }
}
}
Response:
public class Response
{
public int ResponseID { get; set; }
public int UserID { get; set; }
public int QuestionID { get; set; }
public string AnswerValue { get; set; }
public int ReviewID { get; set; }
public virtual Question Question { get; set; }
}
Steps:
public Step()
{
this.Questions = new List<Question>();
}
public int StepID { get; set; }
public int ReviewID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int StepOrder { get; set; }
public virtual ICollection<Question> Questions { get; set; }
The issue is that you're getting the question from the responses, so you're only getting questions that have responses. If you get the questions for each step and then the response for each question, it should work.
var steps = from s in db.Steps
orderby s.StepOrder
select new Quiz
{
StepID = s.StepID,
Title = s.Title,
Results = from question in s.Questions
orderby question.DisplayOrder
select new Result
{
QuestionID = question.QuestionID,
DisplayOrder = question.DisplayOrder,
Choices = question.Choices,
ControlType = question.ControlType,
QuestionText = question.QuestionText,
AnswerValue = question.Responses
.Where(r => r.ReviewID == id)
.Select(r => r.AnswerValue)
.FirstOrDefault()
}
};
Not very pretty... but does what it should ;)
var result =
from step in db.Steps
let questions =
db.Questions.Where(item => item.StepID == step.StepID)
let responses =
db.Responses.Where(item =>
item.ReviewID == id
&& questions.Any(q => q.QuestionID == item.QuestionID))
select new Quiz
{
StepID = step.StepID,
Title = step.Title,
Results =
from question in questions.OrderBy(item => item.DisplayOrder)
select new Result
{
QuestionID = question.QuestionID,
DisplayOrder = question.DisplayOrder,
Choices = question.Choices,
ControlType = question.ControlType,
QuestionText = question.QuestionText,
AnswerValue =
responses.Any(item => item.QuestionID == question.QuestionID)
? responses.First(item =>
item.QuestionID == question.QuestionID).AnswerValue
: null
}
};

Resources