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
}
Related
I want to have one class that has common information; CommonData class will be used in all tables:
public class CommonData
{
public string CreatedBy { get; set; } = "";
public string ModifiedBy { get; set; } = "";
public Nullable<DateTime> CreateDate { get; set; } = DateTime.Now;
public Nullable<DateTime> ModifiedDate { get; set; } = DateTime.Now;
}
Person class:
public class Person
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
}
I know I could do this if I put all of the data in a common class
public class CommonClass
{
public string Id { get; set; }
public string CreatedBy { get; set; } = "";
public string ModifiedBy { get; set; } = "";
public Nullable<DateTime> CreateDate { get; set; } = DateTime.Now;
public Nullable<DateTime> ModifiedDate { get; set; } = DateTime.Now;
}
If I inherit from the common class
public class Person : CommonClass
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
}
The problem is that I have looking at the table it creates and I feel that their must be a better way to do this. When the table is created it puts all of the CommonData in the first fields of the table then it put all of the specific table data. It makes it a mess.
I have tried this to make this but this didn't work I like to have this data in a CommonData object connected to the Person class. This would be the ideal scenario but I don't know how to achieve this.
public class Person
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string ZipCode { get; set; }
public string Phone { get; set; }
public CommonData CommonData {get;set;}
}
When I input the data on the form I get an error saying "when converting a string to datetime, parse the string to take the date before putting each variable into the DateTime object". I tried changing the string format and hardcoded the viewModel.Date, viewModel.Time but I still get an error when can anyone suggest an way of overcoming this?
public ActionResult Create(GigFormViewModel viewModel)
{
var artistId = User.Identity.GetUserId();
var artist = _context.Users.Single(u => u.Id == artistId);
var genre = _context.Genres.Single(g => g.Id == viewModel.Genre);
var gig = new Gig
{
Àrtist = artist,
DateTime = DateTime.Parse(string.Format("{0}{1}", viewModel.Date, viewModel.Time)),
Genre = genre,
Venue = viewModel.Venue
};
_context.Gigs.Add(gig);
_context.SaveChanges();
return RedirectToAction("Index", "Home");
}
public class Gig
{
public int Id { get; set; }
[Required]
public ApplicationUser Àrtist { get; set; }
public DateTime DateTime { get; set; }
[Required]
[StringLength(255)]
public string Venue { get; set; }
[Required]
public Genre Genre { get; set; }
}
public class GigFormViewModel
{
public string Venue { get; set; }
public string Date { get; set; }
public string Time { get; set; }
public int Genre { get; set; }
public IEnumerable<Genre> Genres { get; set; }
}
The problem is here:
DateTime = DateTime.Parse(string.Format("{0}{1}", viewModel.Date, viewModel.Time)),
you should put "space" between {0} and {1}:
DateTime = DateTime.Parse(string.Format("{0} {1}", viewModel.Date, viewModel.Time)),
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
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
I am attempting to update a member, which has quite a few relationships, but receive an error saying that An entity object cannot be referenced by multiple instances of IEntityChangeTracker. Below are the various models and controllers that I have written. Any suggestions on how to correct this would be appreciate.
Member Model
public partial class Member
{
NCOWW_DB db = new NCOWW_DB();
public Member()
{
this.Contacts = new HashSet<Contact>();
this.Utilities = new HashSet<Utility>();
}
public int MemberID { get; set; }
[Display(Name = "Member Name")]
[Required]
public string Name { get; set; }
[Display(Name = "Member Number")]
public string Number { get; set; }
[Display(Name = "Mutual Aid Agreement On File")]
public bool MutualAid { get; set; }
[Display(Name = "Type ID")]
public Nullable<int> TypeID { get; set; }
[ForeignKey("TypeID")]
public virtual UtilityType MemberType { get; set; }
[Display(Name = "Water Population")]
public Nullable<int> WaterPopulation { get; set; }
[Display(Name = "Wastewater Population")]
public Nullable<int> WastewaterPopulation { get; set; }
private Address _Address = new Address();
public Address Address { get { return _Address; } set { _Address = value; } }
private Coordinates _Coordinates = new Coordinates();
public Coordinates Coordinates { get { return _Coordinates; } set { _Coordinates = value; } }
[NotMapped]
public double Distance { get; set; }
public bool Deleted { get; set; }
[Display(Name = "Enable Member")]
public bool Enabled { get; set; }
private DateTime _createdOn = DateTime.UtcNow;
public DateTime CreatedOn { get { return _createdOn; } set { _createdOn = value; } }
private DateTime _modifiedOn = DateTime.UtcNow;
public DateTime ModifiedOn { get { return _modifiedOn; } set { _modifiedOn = value; } }
public System.Guid ModifiedBy { get; set; }
//public virtual ICollection<Utility> Contacts { get; set; }
private ICollection<Contact> _Contacts;
public virtual ICollection<Contact> Contacts {
get
{
return (from c in db.Contact
where (c.MemberID == MemberID && c.Deleted == false)
select c).OrderBy(c => c.FirstName).ToList();
}
set
{
_Contacts = value;
}
}
//public virtual ICollection<Utility> Utilities { get; set; }
private ICollection<Utility> _Utilities;
public virtual ICollection<Utility> Utilities
{
get
{
return (from u in db.Utility
where (u.MemberID == MemberID && u.Deleted == false)
select u).OrderBy(u => u.Name).ToList();
}
set
{
_Utilities = value;
}
}
}
Utility Model
public partial class Utility
{
NCOWW_DB db = new NCOWW_DB();
public Utility()
{
this.Contacts = new HashSet<Contact>();
this.Resources = new HashSet<UtilityResource>();
}
[Key]
public int UtilityID { get; set; }
[Display(Name="Member")]
[Required]
public int MemberID { get; set; }
[ForeignKey("MemberID")]
public virtual Member Member { get; set; }
[ForeignKey("UtilityID")]
public virtual ICollection<UtilityResource> Resources { get; set; }
[ForeignKey("UtilityID")]
private ICollection<Contact> _Contacts;
public virtual ICollection<Contact> Contacts
{
get
{
return (from c in db.Contact
where (c.MemberID == MemberID && c.Deleted == false)
select c).OrderBy(c => c.FirstName).ToList();
}
set
{
_Contacts = value;
}
}
//public virtual ICollection<Contact> Contacts { get; set; }
[Required]
public string Name { get; set; }
private Address _Address = new Address();
public Address Address { get { return _Address; } set { _Address = value; } }
private Coordinates _Coordinates = new Coordinates();
public Coordinates Coordinates { get { return _Coordinates; } set { _Coordinates = value; } }
[Display(Name = "Utility Type")]
public int? TypeID { get; set; }
[ForeignKey("TypeID")]
[Display(Name = "Utility Type")]
public virtual UtilityType UtilityType { get; set; }
[Display(Name = "Region")]
public int? RegionID { get; set; }
[Display(Name = "County")]
public int? CountyID { get; set; }
private UtilityInfo _WaterInfo = new UtilityInfo();
[Display(Name="Water Information")]
public UtilityInfo WaterInfo { get { return _WaterInfo; } set { _WaterInfo = value; } }
private UtilityInfo _WastewaterInfo = new UtilityInfo();
[Display(Name = "Wastewater Information")]
public UtilityInfo WastewaterInfo { get { return _WastewaterInfo; } set { _WastewaterInfo = value; } }
[NotMapped]
public double Distance { get; set; }
private bool _enabled = true;
public bool Enabled { get { return _enabled; } set { _enabled = value; } }
public bool Deleted { get; set; }
private DateTime _createdOn = DateTime.UtcNow;
public DateTime CreatedOn { get { return _createdOn; } set { _createdOn = value; } }
private DateTime _modifiedOn = DateTime.UtcNow;
public DateTime ModifiedOn { get { return _modifiedOn; } set { _modifiedOn = value; } }
public Guid ModifiedBy { get; set; }
}
Contact Model
public partial class Contact
{
public Contact()
{
this.Phones = new HashSet<ContactPhone>();
}
[Key]
public int ContactID { get; set; }
public Nullable<Guid> UserID { get; set; }
[Display(Name = "Member")]
public int MemberID { get; set; }
public Nullable<int> UtilityID { get; set; }
public string Username { get; set; }
[Display(Name = "First Name")]
[Required]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[Required]
public string LastName { get; set; }
[NotMapped]
public string FullName { get { return FirstName + " " + LastName; } }
[NotMapped]
public string FullNameLastNameFirst { get { return LastName + ", " + FirstName; } }
[Display(Name = "Contact Type")]
public string Type { get; set; }
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*")]
[Required]
public string Email { get; set; }
[ForeignKey("ContactID")]
public virtual ICollection<ContactPhone> Phones { get; set; }
[NotMapped]
[Display(Name = "Grant Website Access")]
public bool WebsiteAccess { get; set; }
public bool Deleted { get; set; }
private DateTime _createdOn = DateTime.UtcNow;
public DateTime CreatedOn { get { return _createdOn; } set { _createdOn = value; } }
private DateTime _modifiedOn = DateTime.UtcNow;
public DateTime ModifiedOn { get { return _modifiedOn; } set { _modifiedOn = value; } }
public System.Guid ModifiedBy { get; set; }
public virtual Member Member { get; set; }
public virtual Utility Utility { get; set; }
[NotMapped]
public string Password { get; set; }
[NotMapped]
[Compare("Password")]
[Display(Name = "Confirm Password")]
public string PasswordConfirm { get; set; }
}
public partial class ContactPhone
{
[Key]
public int PhoneID { get; set; }
public int ContactID { get; set; }
public string Number { get; set; }
public string Type { get; set; }
}
Member Edit Controller
private NCOWW_DB db = new NCOWW_DB(); //dbContext
public ActionResult Edit(Member member)
{
try
{
if (ModelState.IsValid)
{
member.ModifiedBy = CurrentUser;
member.ModifiedOn = DateTime.UtcNow;
db.Entry(member).State = EntityState.Modified; <--ERROR OCCURS HERE!
db.SaveChanges();
//RETURN TO DASHBOARD
return RedirectToAction("Index");
}
}
catch (Exception err)
{
/*catch error code*/
}
return View(member);
}
UPDATE
Based on the answer below, I have modified my code in an attempt to remove the ill-placed NCOWW_DB db = new NCOWW_DB(). However, this does not solve the problem as I am unsure how to pass the dbContext properly. Regardless, this is where the code currently stands:
UPDATED MEMBER MODEL
...
private ICollection<Contact> _Contacts;
public virtual ICollection<Contact> Contacts {
get
{
return MemberFunctions.LoadMemberContacts(MemberID);
}
set
{
_Contacts = value;
}
}
private ICollection<Utility> _Utilities;
public virtual ICollection<Utility> Utilities
{
get
{
return MemberFunctions.LoadMemberUtilities(MemberID);
}
set
{
_Utilities = value;
}
}
}
public static class MemberFunctions
{
public static ICollection<Contact> LoadMemberContacts(int memberID)
{
NCOWW_DB db = new NCOWW_DB();
return (from c in db.Contact
where (c.MemberID == memberID && c.UtilityID == null && c.Deleted == false)
select c).OrderBy(c => c.FirstName).ToList();
}
public static ICollection<Utility> LoadMemberUtilities(int memberID)
{
NCOWW_DB db = new NCOWW_DB();
return (from u in db.Utility
where (u.MemberID == memberID && u.Deleted == false)
select u).OrderBy(u => u.Name).ToList();
}
}
You are working very carelessly with multiple context (that you even don't dispose properly). In every Member and Utility entity you instantiate a new context:
NCOWW_DB db = new NCOWW_DB();
and use it in property getters like Member.Contacts (even without a guard if the collection hasn't been loaded already, so you'll get a DB query everytime you access the property).
Your particular exception occurs because db.Entry(member).State = EntityState.Modified will attach the member entity and all related entities to the context db. In order to attach the related Contact entities EF must touch the property getter member.Contacts which will run the query in your getter that will attach the Contact entities to another context, namely the one you instantiate in the member entity. Attaching the same object to two different contexts is not allowed and causes the exception.
You should refactor your code somehow to make sure that you only use the same context instance for a DB operation. Especially I'd stay away from creating context members inside an entity. The better place for queries like that are repositories or data access or service layers or whatever you like to call them.
When you set property of member it automatically get modified state so statement
db.Entry(member).State = EntityState.Modified; is not needed.
But i'm not seeing where you attach your entity to dbcontext and it can be another problem in your code.
It seems that you should call instead
db.Members.Attach(member);