I am facing the below issues when I try to achieve the requirement.
In controller I have used automapper to map "Viewmodel" class with "Entities" class but I am getting exception.I used Automapper exception class to catch the exception, the result is :
Missing type map configuration or unsupported mapping
Mapping types:
EmpDetails -> StaffMember
Org.Entities.EmpDetails -> Org.Web.Models.StaffMember
Destination path:
List`1[0]
Source value:
Org.Entities.EmpDetails
In Data access layer when I am adding the value to dropdown I am getting Exception , Please advise me whether the classes are well formed/designed and help me out to get rid of these issues.
PFB Screen shots and Codes:
Exception ScreenShots
Exception for Automapper in Controller:
Exception For DropDown in DAL:
Code:
Controller:-
EmployeeStatus oStatusBL = new EmployeeStatus(); // Business layer class
public ActionResult Index()
{
EmpStatusDetails oStaff = oStatusBL.getEmpStatusDetails();
StaffMemberList oLsit = new StaffMemberList();
Mapper.CreateMap<EmpStatusDetails, StaffMemberList>();
Mapper.Map<EmpStatusDetails, StaffMemberList>(oStaff); // Exception Occurs here
ViewBag.StateDropDown = oStatusBL.GetStateDropDown();
return View(oLsit);
}
ViewModel:-
public class StaffMember
{
public string FullName { get; set; }
public string FullAddress { get; set; }
public string StatusMessage { get; set; }
public DateTime DateCreated { get; set; }
public int UserID { get; set; }
}
public class StaffMemberList
{
public List<StaffMember> StaffDetails { get; set; }
public Status StatusDetails { get; set; }
public Users UserDetails { get; set; }
}
public class Status
{
[Required(ErrorMessage = "Please select Name")]
public int UserID { get; set; }
[Required(ErrorMessage = "Status Message is Required")]
[RegularExpression(#"^[\w\d]+$", ErrorMessage = "Avoid Special characters")]
[StringLength(250, ErrorMessage = "Exceeds 250 Character")]
public string Statusmessage { get; set; }
public DateTime DateCreated { get; set; }
public IEnumerable<SelectListItem> DropDownNameList { get; set; }
}
public class Users
{
public int UserID { get; set; }
[Required(ErrorMessage = "First Name is Required")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Last Name is Required")]
public string LastName { get; set; }
[Required(ErrorMessage = "Address is Required")]
[RegularExpression("^[a-zA-Z0-9\\s,'-]*$", ErrorMessage = "Invalid Address")]
[StringLength(250, ErrorMessage = "Exceeds 250 Character")]
public string Address { get; set; }
[Required(ErrorMessage = "City is Required")]
[RegularExpression("^[a-zA-Z]+$", ErrorMessage = "Invalid City")]
[StringLength(150, ErrorMessage = "Exceeds 150 Character")]
public string City { get; set; }
[Required(ErrorMessage = "State is Required")]
[RegularExpression("^[a-zA-Z]+$", ErrorMessage = "Invalid State")]
public string State { get; set; }
[Required(ErrorMessage = "Zip is Required")]
[RegularExpression("^[0-9]{5}$", ErrorMessage = "Invalid Zipcode")]
public int? Zip { get; set; }
public DateTime DateCreated { get; set; }
}
EntitiesLayer:-
public class EmpDetails
{
public string FullName { get; set; }
public string FullAddress { get; set; }
public string StatusMessage { get; set; }
public DateTime DateCreated { get; set; }
public int UserID { get; set; }
public StatusEntity StatusDetails { get; set; }
}
public class EmpStatusDetails
{
public List<EmpDetails> StaffDetails { get; set; }
public StatusEntity StatusDetails { get; set; }
public UserEntity UserDetails { get; set; }
}
public class StatusEntity
{
public int UserID { get; set; }
public string Statusmessage { get; set; }
public DateTime DateCreated { get; set; }
public IEnumerable<SelectListItem> DropDownNameList { get; set; }
}
public class UserEntity
{
public int UserID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public int? Zip { get; set; }
public DateTime DateCreated { get; set; }
}
BusinessLayer:-
StaffDetailsDAL oDal = new StaffDetailsDAL();
public EmpStatusDetails getEmpStatusDetails()
{
return oDal.EmployeeStatusAndDetails();
}
DataAccessLayer:-
public EmpStatusDetails EmployeeStatusAndDetails()
{
EmpStatusDetails oEmp = new EmpStatusDetails(); // Entity layer class
List<User> us = dbContext.Users.Select(o => o).ToList();
List<EmpDetails> oStaffList = (from usrs in dbContext.Users
join stats in dbContext.StatusUpdates on usrs.UserID equals stats.UserID
where stats.Statusmessage !=null
select new EmpDetails { FullName = usrs.FirstName + " " + usrs.LastName, FullAddress = usrs.Address + "," + usrs.State + "," + usrs.City + "," + SqlFunctions.StringConvert((double)usrs.Zip), StatusMessage = stats.Statusmessage, DateCreated = (DateTime)stats.DateCreated, UserID = usrs.UserID }
).OrderBy(x => x.DateCreated).ToList<EmpDetails>();
IEnumerable<SelectListItem> oList = (from val in oStaffList
select new SelectListItem { Text = val.FullName, Value = val.UserID.ToString() }).ToList();
oEmp.StaffDetails = oStaffList;
oEmp.StatusDetails.DropDownNameList = oList; // Exception Occurs here
return oEmp;
}
You need to create a mapping for the collection of StaffDetails
Related
In the following model class I am attempting to create a calculated field called FullAddress. I am able to get it to work, but right now it displays the values and not the text for 4 different ID fields. I would like to display the text instead of the value for the following fields:
TLRoadDirectionID
TLRoadTypeID
VendorAddUnitTypeOneID
VendorAddUnitTypeTwoID
I received some great help earlier on correctly creating FullAddress, so I know that if I were to change the fields to:
TLRoadDirection.Direction
TLRoadType.RdType
TLUnitTypeOne.UnitType
TLUnitTypeTwo.UnitType
then it works as expected, but only if all of those 4 fields contain a value and are not null or empty. But these fields will not always have values for each record.
So, how can I modify this calculated field to show the text for each when there is text to show, and not get a null reference exception when any or all of these 4 fields are null or empty?
Below is the class (please let me know if additional information is required):
using System;
using System.ComponentModel.DataAnnotations;
using System.Web;
namespace VendorMgr.Models
{
public class Vendor
{
[Display(Name = "Vendor ID")]
public int ID { get; set; }
private string _createdBy = HttpContext.Current.User.Identity.Name;
[Required]
[Display(Name = "Created By")]
public string VendorCreatedBy
{
get
{
return (_createdBy == HttpContext.Current.User.Identity.Name) ? HttpContext.Current.User.Identity.Name : _createdBy;
}
set
{
_createdBy = HttpContext.Current.User.Identity.Name;
}
}
private DateTime _createdOn = DateTime.Now;
[Required]
[Display(Name = "Date Created")]
[DataType(DataType.DateTime)]
public DateTime VendorCreatedDt
{
get
{
return (_createdOn == DateTime.Now) ? DateTime.Now : _createdOn;
}
set
{
_createdOn = value;
}
}
[Required]
[StringLength(128)]
[Display(Name = "Vendor Name")]
public string VendorName { get; set; }
[Display(Name = "Phone Number")]
[DataType(DataType.PhoneNumber)]
[RegularExpression(#"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid phone number")]
public string VendorPhoneNumber { get; set; }
[Display(Name = "Email")]
[StringLength(255)]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string VendorEmail { get; set; }
[Display(Name = "Address Number")]
[StringLength(10)]
public string VendorAddNum { get; set; }
[Display(Name = "Direction")]
public int? TLRoadDirectionID { get; set; }
[Display(Name = "Road Name")]
[StringLength(128)]
public string VendorAddName { get; set; }
[Display(Name = "Road Type")]
public int? TLRoadTypeID { get; set; }
[Display(Name = "Unit Type")]
public int? VendorAddUnitTypeOneID { get; set; }
[Display(Name = "Unit")]
[StringLength(20)]
public string VendorAddUnitOne { get; set; }
[Display(Name = "Unit Type")]
public int? VendorAddUnitTypeTwoID { get; set; }
[Display(Name = "Unit")]
[StringLength(20)]
public string VendorAddUnitTwo { get; set; }
[Display(Name = "Full Address")]
public string FullAddress
{
get
{
return $"{VendorAddNum} {TLRoadDirectionID} {VendorAddName} {TLRoadTypeID} {VendorAddUnitTypeOneID} {TLUnitTypeOne.UnitType} {VendorAddUnitOne} {VendorAddUnitTypeTwoID} {VendorAddUnitTwo}";
}
}
[Display(Name = "City")]
[StringLength(128)]
public string VendorAddCity { get; set; }
[Display(Name = "State")]
public int? TLStateAcronymnID { get; set; }
[Display(Name = "Zip Code")]
[StringLength(20)]
public string VendorZipCode { get; set; }
[Display(Name = "Country")]
public int? TLCountryID { get; set; }
[Display(Name = "Active")]
public bool VendorActive { get; set; }
public virtual TLRoadDirection TLRoadDirection { get; set; }
public virtual TLRoadType TLRoadType { get; set; }
public virtual TLUnitType TLUnitTypeOne { get; set; }
public virtual TLUnitType TLUnitTypeTwo { get; set; }
public virtual TLStateAcronymn TLStateAcronymn { get; set; }
public virtual TLCountry TLCountry { get; set; }
}
}
[Display(Name = "Full Address")]
public string FullAddress
{
get
{
IEnumerable<string> allFields = new[] { VendorAddNum, TLRoadDirectionID, VendorAddName, TLRoadTypeID, VendorAddUnitTypeOneID, TLUnitTypeOne.UnitType, VendorAddUnitOne, VendorAddUnitTypeTwoID, VendorAddUnitTwo };
return String.Join(" ", allFields.Where<string>(x => x != null));
}
}
I chose to just handle this in the view instead of the model class.
I have a linq statement that combines Residents and Requests table like so
var resident = await _context.Resident
.Include(s => s.Requests)
.FirstOrDefaultAsync(m => m.ID == id);
The problem is that all requests show up even those that are not related to the Resident.
I have tried adding a Where statement but still getting all requests.
var resident = await _context.Resident
.Include(s => s.Requests)
.Where(s =>s.UserID == "f7c6ceef-663f-48af-9a84-b0a3d2a97601")
.FirstOrDefaultAsync(m => m.ID == id);
For reference this is the Resident Model Class
public class Resident
{
public Resident()
{
this.CreatedAt = DateTime.Now;
}
public int ID { get; set; }
public string UserID { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Street Address")]
public string StreetAddress { get; set; }
[Required]
[Display(Name = "Postal Code")]
public string PostalCode { get; set; }
[Required]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Required]
[Display(Name = "Number of Cameras")]
public int CameraQty { get; set; }
public DateTime CreatedAt { get; set; }
public string Latlng { get; set; }
public ICollection<Camera> Cameras { get; set; }
public ICollection<Request> Requests { get; set; }
}
This is the Request Model Class
using System.ComponentModel.DataAnnotations;
namespace MVC_NeighbourhoodCamera.Models
{
public class Request
{
public Request()
{
this.CreatedAt = DateTime.Now;
}
public int ID { get; set; }
public int ResidentID { get; set; }
public string UserID { get; set; }
public DateTime StartDateTime { get; set; }
public DateTime EndDateTime { get; set; }
[DataType(DataType.MultilineText)]
public string Details { get; set; }
public Boolean Completed { get; set; }
public Boolean Active { get; set; }
public DateTime CreatedAt { get; set; }
public Resident Resident { get; set; }
}
}
You do not have foreign key properly set in Resident->Requests one-to-many relationship.
Fix your Request class as following by adding ForeignKeyAttribute (+make migration and run it in to the db):
public class Request
{
//Other properties
..
public int ResidentID { get; set;}
ForeignKey["ResidentID"]
public Resident Resident { get; set;}
}
More info can be found i.e here.
PostEntity
[Table("Posts")]
public class PostEntity
{
public PostEntity()
{
ViewsCount = 0;
VotesCount = 0;
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int PostId { get; set; }
[Required]
public DateTime CreatedAt { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Text { get; set; }
[Required]
public string Permalink { get; set; }
[Required]
public string CreatedByUserId { get; set; }
[ForeignKey("CreatedByUserId")]
public UserEntity CreatedByUser { get; set; }
public List<PostTagEntity> PostTags { get; set; }
public List<PostVoteEntity> PostVotes { get; set; }
public List<PostSpamFlagEntity> PostSpamFlags { get; set; }
public int ViewsCount { get; set; }
public int VotesCount { get; set; }
[Required]
public string PostType { get; set; }
[Required]
public string PostState { get; set; }
public int? CategoryId { get; set; }
[ForeignKey("CategoryId")]
public CategoryEntity Category { get; set; }
public List<ResponseEntity> Responses { get; set; }
}
User entity
public class UserEntity : IdentityUser
{
public async Task<IdentityResult> GenerateUserIdentityAsync(UserManager<UserEntity> manager, string authenticationType)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateAsync(this, authenticationType);
// Add custom user claims here
return userIdentity;
}
public String Name { get; set; }
public String Gender { get; set; }
public String ProfilePictureUrl { get; set; }
public String InfoMessage { get; set; }
public String Country { get; set; }
public DateTime BirthDate { get; set; }
public List<PostEntity> Posts { get; set; }
public string LockoutReason { get; set; }
public string LockoutAdditionalComment { get; set; }
}
The problem:
PostEntity post = new PostEntity();
post.CategoryId = request.CategoryId;
post.CreatedAt = DateTime.UtcNow;
post.CreatedByUserId = user.Id; // <-- doesn't work
post.PostType = "B";
post.Title = request.Title;
post.PostState = "N";
post.Permalink = Permalink.Create(request.Title);
post.Text = request.Content;
UpdateBlogpostTags(post, request.Tags);
m_context.Posts.Add(post);
m_context.SaveChanges();
I get:
Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while updating the entries. See the inner exception for details.
Microsoft.Data.Sqlite.SqliteException : SQLite Error 19: 'FOREIGN KEY constraint failed'.
But if I change:
post.CreatedByUserId = user.Id;
to:
post.CreatedByUser = user;
It inserts successfully.
This also works but feels wrong:
post.CreatedByUser = new UserEntity(){
Id = user.Id
};
What am I missing?
I'm trying to update a many-to-many relationship. I have two models, diary and tags. The model diary contains a list of tags and tags contains a list of diaries. But whenever I try to add another tag to an existing list or change an existing one I get thrown an exception:
The entity type List`1 is not part of the model for the current context.
Does my way of updating even work on collections? Or is there another approach I should be looking at?
Diary Model
public class Diary
{
[Key]
public int IdDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
public string NameDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
public bool Locked { get; set; }
public ICollection<Entry> Entries { get; set; }
[DataType(DataType.MultilineText)]
[Required(ErrorMessage = "This field is required")]
public string Summary { get; set; }
public string ImageUrl { get; set; }
public ICollection<Tag> Tags { get; set; }
}
Entry Model
public class Entry
{
[Key]
public int IdEntry { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
[DataType(DataType.MultilineText)]
public string EntryText { get; set; }
[ForeignKey("Diary_IdDiary")]
public Diary Diary { get; set; }
public int Diary_IdDiary { get; set; }
public string EntryName { get; set; }
}
Tag Model
public class Tag
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<Diary> Diaries { get; set; }
}
Update Method
public void UpdateDiary(Diary updatedDiary)
{
var searchResult = SearchDiary(updatedDiary);
if (searchResult != null)
{
updatedDiary.IdDiary = searchResult.IdDiary;
_context.Entry(searchResult).CurrentValues.SetValues(updatedDiary);
_context.Entry(searchResult.Tags).CurrentValues.SetValues(updatedDiary.Tags);
_context.SaveChanges();
}
}
SearchDiary Method
public Diary SearchDiary(Diary searchDiary)
{
var queryResult =
_context.Diaries.Include(d => d.Entries).Include(d => d.Tags)
.Where(d => (d.NameDiary == searchDiary.NameDiary && d.CreationDate == searchDiary.CreationDate) || d.IdDiary == searchDiary.IdDiary);
return queryResult.FirstOrDefault();
}
Thank you for reading
Here is one way:
DiaryModel
public class Diary
{
[Key]
public int IdDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
public string NameDiary { get; set; }
[Required(ErrorMessage = "This field is required")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
public bool Locked { get; set; }
public virtual ICollection<Entry> Entries { get; set; }
[DataType(DataType.MultilineText)]
[Required(ErrorMessage = "This field is required")]
public string Summary { get; set; }
public string ImageUrl { get; set; }
public ICollection<Tag> Tags { get; set; }
}
EntryModel
public class Entry
{
[Key]
public int IdEntry { get; set; }
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime CreationDate { get; set; }
[DataType(DataType.MultilineText)]
public string EntryText { get; set; }
[ForeignKey("Diary_IdDiary")]
public virtual Diary Diary { get; set; }
public int Diary_IdDiary { get; set; }
public string EntryName { get; set; }
}
For Search
public Diary SearchDiary(int DiaryId)
{
return _context.Diaries
.Include(p => p.Entries)
.Include(p => p.Tags)
.FirstOrDefault(p => p.IdDiary == DiaryId);
}
For Update
public void UpdateDiary(Diary Diary)
{
_context.Update(Diary);
_context.SaveChanges();
}
You should pass the modified Diary object to the update functions.
I have two entities in my database:Patient and Doctor, which contains one-to-many relationship.Classes are as follows:
public partial class Doctor
{
public Doctor()
{
this.Patients = new HashSet<Patient>();
}
public int DoctorID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Country { get; set; }
public System.DateTime Birthday { get; set; }
public byte[] Photo { get; set; }
public string Password { get; set; }
public string PasswordSalt { get; set; }
public int SpecialityID { get; set; }
public virtual Speciality Speciality { get; set; }
public virtual ICollection<Patient> Patients { get; set; }
}
public partial class Patient
{
public int PatientID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
public string MaritalStatus { get; set; }
public System.DateTime Birthday { get; set; }
public string Phone { get; set; }
public int DoctorID { get; set; }
public System.DateTime EntryDate { get; set; }
public virtual Doctor Doctor { get; set; }
public virtual PatientAddress PatientAddress { get; set; }
}
This is code for adding a patient to a doctor.
public ActionResult AddPatient(PatientViewModel patientVM)
{
using (PeopleCareEntities PeopleEntities=new PeopleCareEntities())
{
PatientAddress patientAddress = Mapper.Map<PatientViewModel, PatientAddress>(patientVM);
Patient patient = Mapper.Map<PatientViewModel, Patient>(patientVM);
int currentDoctor = ((Doctor)Session["Doctor"]).DoctorID;
//problem is here
Doctor doctor=PeopleEntities.Doctors.Single(a=>a.DoctorID==currentDoctor);
var doctorPatients = doctor.Patients.FirstOrDefault(a=>a.Email==patientVM.Email);
if (doctorPatients==null)
{
patient.EntryDate = DateTime.Now;
patient.DoctorID = doctor.DoctorID;
doctor.Patients.Add(patient);
PeopleEntities.SaveChanges();
patientAddress.PatientID = patient.PatientID;
PeopleEntities.PatientAddresses.Add(patientAddress);
PeopleEntities.SaveChanges();
return Json(new { Message = "Patient added successfully !" }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { Message="Patient already exist !" }, JsonRequestBehavior.AllowGet);
}
}
}
Adding a patient in database works perfectly,but doctor.Patients has always Count=0. in debug mode.
Thanks in advance.
When loading the doctor entity try this:
Doctor doctor=PeopleEntities.Doctors.Single(a => a.DoctorID == currentDoctor)
.Include(a => a.Patients);