Unable to add data into database MVC 5 code first approach - c#

I am using entity framework 6 with code first approach. I have 3 model classes
User,country and city. I am trying to add user to database but unable to do it.
Here is my user class.
public class User
{
public int userId { get; set; }
public int cityId { get; set; }
public String firstName { get; set; }
public String lastName { get; set; }
public String gender { get; set; }
public String email { get; set; }
public String password { get; set; }
public String photo { get; set; }
public DateTime joinDate { get; set; }
//public City city { get; set; }
//public Country country { get; set; }
public virtual City city { get; set; }
private String FullName
{
get { return firstName + lastName; }
}
}
Controller method
[HttpPost]
public ActionResult Register(User user)
{
User reg = new User() {
cityId = 2,
firstName = "U",
lastName = "v",
email = "u33#gmail.com",
password = "123",
gender = "Male",
photo = "asd",
};
try
{
db.Users.Add(reg);
db.SaveChanges();
// TODO: Add insert logic here
return View("Index","Home");
}
catch
{
return RedirectToAction("Index", "Home");
// return View("Register", user);
}
// return View("Register", user);
}
it goes to catch statement and does not add into database.
Catch Error
Exception:Thrown: "An error occurred while updating the entries. See the inner exception for details." (System.Data.Entity.Core.UpdateException)
A System.Data.Entity.Core.UpdateException was thrown: "An error occurred while updating the entries. See the inner exception for details."
Time: 10/21/2015 5:25:41 PM
Thread:Worker Thread[5576]

Since DateTime is a value type you need to use a Nullable<DateTime> (or DateTime?) when you do not want to set it because the DateTime.MinValue (default value of a DateTime) is not in the range of acceptable values of many Sql DB DateTime field.
Fix :
public class User
{
public int userId { get; set; }
public int cityId { get; set; }
public String firstName { get; set; }
public String lastName { get; set; }
public String gender { get; set; }
public String email { get; set; }
public String password { get; set; }
public String photo { get; set; }
public DateTime? joinDate { get; set; }
//public City city { get; set; }
//public Country country { get; set; }
public virtual City city { get; set; }
private String FullName
{
get { return firstName + lastName; }
}
}
Th second solution is to assign a value to the joinDate when you create the Person

Related

Post item into database without filling the foreign key

I am creating a Web API model for banking system each branch have a managerId which is a foreign key to the users table.
When I want to post a new branch, I have to fill all the columns for branch and the manager. How can I only insert branch columns?
Branches entity:
public class Branch
{
public int Id { get; set; }
public string BranchName { get; set; }
public string? PhoneNumber { get; set; }
public User BranchManager { get; set; }
public ICollection<Device> Devices { get; set; }
}
Users entity:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public int ? SuperviseID { get; set; }
public UserTypes UserType { get; set; }
[ForeignKey("SuperviseID")]
public User? Supervise { get; set; }
public ICollection<Branch>? Branches { get; set; }
}
My code:
public void PostBranch(Branch branch)
{
var db = new OrganizationDbContext();
db.Add(branch);
db.SaveChanges();
}
Post request body:
{
"id": 5,
"branchName": "Bank",
"phoneNumber": "9999999",
"branchManagerId": 7
}
When I left other columns empty, I get an error:
SqlException: Cannot insert the value NULL into column
I find where the problem is:
public void PostBranch(Branch branch)
{
var db = new OrganizationDbContext();
db.Add(branch);
db.SaveChanges();
}
db.Add(branch) should convert to db.Branches.Add(branch)

Entity error when there is no input DateTimePicker

internal class Person
{
[Key]
public int PersonId { get; set; }
[Required]
[StringLength(20)]
public string SurName { get; set; }
[Required]
[StringLength(20)]
public string LastName { get; set; }
[Required]
public DateTime BirthDate { get; set; }
public DateTime DeathDate { get; set; }
[Required]
public Gender gender { get; set; }
[Required]
[StringLength(20)]
public string Father { get; set; }
[Required]
[StringLength(20)]
public string Mother { get; set; }
public Person(string surName, string lastName, DateTime birthDate, Gender gender, string father, string mother)
{
SurName = surName;
LastName = lastName;
BirthDate = birthDate;
this.gender = gender;
Father = father;
Mother = mother;
}
I have dont have [required] by DeathDate, still it only crashes when there is no input for DeathDate.
The error shown in debugger when i want to add them to the database
Exception thrown: 'System.Data.SqlClient.SqlException' in
EntityFramework.dll
private void AddPersonButton_Click(object sender, RoutedEventArgs e)
{
if (DeathDateDatePicker.SelectedDate == null)
{
Person personsntDeath = new Person(
SurNameTextBlock.Text.Trim(),
LastNameTextBlock.Text.Trim(),
BirthDateDatePicker.SelectedDate.Value,
(Gender)SexComboBox.SelectedItem,
FatherTextBox.Text.Trim(),
MotherTextBox.Text.Trim());
personsntDeath.InsertIntoDB();
}
else
{
Person persons = new Person(
SurNameTextBlock.Text.Trim(),
LastNameTextBlock.Text.Trim(),
BirthDateDatePicker.SelectedDate.Value,
DeathDateDatePicker.SelectedDate.Value,
(Gender)SexComboBox.SelectedItem,
FatherTextBox.Text.Trim(),
MotherTextBox.Text.Trim());
persons.InsertIntoDB();
}
mainWindow.Content = new PageOverviewPersons(mainWindow);
}
If there is no input in DeathDatePicker i want it to be null in my database. It comes back with the value "{01/01/0001 00:00:00}"
public bool InsertPerson(Person persons)
{
using (DataBaseContext ctx = new DataBaseContext())
{
try
{
ctx.Persons.Add(persons);
ctx.SaveChanges();
return true;
}
catch (Exception)
{
return false;
}
}
}
I am trying to create a family tree program.
DateTime is a value type it can not be null unless you define it as nullable using ? operator
public DateTime? DeathDate { get; set; }
Try to change
public DateTime DeathDate { get; set; }
to
public DateTime? DeathDate { get; set; } //Nullable
And check if its got value by using DateTime?.HasValue property.
if (!DeathDateDatePicker.SelectedDate.HasValue)
{
// Your code here
}

Sharing of Property in a DTO using Category attribute c#

I'm working on Employee Model, it contains all the information about the Employee already I posted the same in How to use the DTO efficiently based on Scenario in C#. How could I share the single property for the multiple groups using Category attribute c#.
For Example:
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string HomePhone { get; set; }
public string MobilePhone { get; set; }
}
I'm having the following four methods for fetching records of Employee
public Employee GetEmployeeName(int id)
{
// The return should contain only FirstName, MiddleName and LastName.
// The rest of the properties should be non-accessable (i.e., Private)
}
public Employee GetEmployeeContacts(int id)
{
// The return should contain only EmailAddress, HomePhone and MobilePhone.
// The rest of the properties should be non-accessable (i.e., Private)
}
public Employee GetEmployeeNameEmail(int id)
{
// The return should contain only FirstName, MiddleName, LastName and EmailAddress.
// The rest of the properties should be non-accessable (i.e., Private)
}
public Employee GetEmployee(int id)
{
// It should return the entire Employee object
}
How could I achieve this? could you please any one help in this regards.
A sample, this is the common use for DTO:
public class EmployeeNameDto
{
public int EmployeeId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
}
public EmployeeNameDto GetEmployeeName(int id)
{
Employee emplpoyee = employeeRepository.Find(id):
return new EmployeeNameDto() {
EmployeeId = emplpoyee.EmployeeId,
FirstName = emplpoyee.FirstName,
MiddleName = emplpoyee.MiddleName,
LastName = emplpoyee.LastName
};
}
Or
public class Employee
{
public int EmployeeId { get; set; }
public string FirstName { get;
set {
if (condition == false)
throw new Exception(" is Read Only !")
}
}
public string MiddleName { get; set; }
public string LastName { get; set; }
public string EmailAddress { get; set; }
public string HomePhone { get; set; }
public string MobilePhone { get; set; }
}

Navigation for One to many relationship does no work in c#

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);

Exception in Automapper Mapping and how to frame the class structure properly

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

Categories

Resources