-1

I'm trying to insert a customer in my database from the create page and I keep getting a null reference. My model is structured like like so:

Model

 public string Name { get; set; }
 ...
 public string FirstName { get { return Name.Substring(0, Name.IndexOf(" ")); } }
 public string LastName { get { return Name.Substring(Name.IndexOf(" ") + 1); } }

My controller is setup like so:

 [HttpPost]
 public ActionResult Create(Customer customer)
 {
      if (ModelState.IsValid)
      {
           Customer add = new Customer();

           add.Name = customer.FirstName + " " + customer.LastName;

           db.Customers.Add(add);
           db.SaveChanges();

I understand that when inserting data, the Name field will return a null because it doesn't have anything in the beginning. How should should I adjust this?

Alfie McNarutoad
  • 368
  • 1
  • 11
  • 20

1 Answers1

0

Use a conditional to check if Name is empty. Use private fields to hold the first and last name records. Mark first and last name as NotMapped if they are not part of the table. NOTE: After setting Name the first time, you will need to edit the Name directly. You won't be able to change first and last name since you are checking if Name exists first.

private string firstName;
private string lastName;  

public string Name { get; set; }
[NotMapped]
public string FirstName { 
   get { return String.IsNullOrEmpty(Name) ? firstName : Name.Substring(0, Name.IndexOf(" ")); }
   set { firstName = value; }
}
[NotMapped]
public string LastName { 
   get { return String.IsNullOrEmpty(Name) ? lastName : Name.Substring(Name.IndexOf(" ") + 1 : );} 
   set { lastName = value; }
}
ATerry
  • 1,832
  • 1
  • 10
  • 17