I want to generate the email when an employee is created using properties (FirstName and LastName) from the base class:
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DOB { get; set; }
public string Phone { get; set; }
}
public class Employee : Person
{
public Employee()
{
Packages = new List<Package>();
}
public string Email { get =>$"{FirstName[0]}.{LastName}@GTravel.com.au"; }
public IEnumerable<Package> Packages { get; set; }
}
So the output should be something like: J.Smith@GTravel.com.au I then want to be able to save this employee into a sql database with Person as the Entity/Table and Employee as the discriminator.
using (var gtmsdb = new GTMSDbContext())
{
var newEmployee = new Employee
{
FirstName = "John",
LastName = "Smith",
DOB = new DateTime(1992, 09, 16),
Phone = "03-1234-567"
};
gtmsdb.People.Add(newEmployee);
gtmsdb.SaveChanges();
}
Shows Employee in debugger with email created
When I run the code it creates the employee with the Email in the correct format and everything but when I try saving to the database it returns the error:
SqlException: Cannot insert the value NULL into column 'Email', table 'GTMSDatabase.dbo.People'; column does not allow nulls. INSERT fails.
I also tried saving the Email as a simple {get; set;} and then hard coded the email:
public string Email { get; set; }
var newEmployee = new Employee
{
FirstName = "John",
LastName = "Smith",
DOB = new DateTime(1992, 09, 16),
Phone = "032166702",
Email ="j.smith@gtravel"
};
gtmsdb.People.Add(newEmployee);
gtmsdb.SaveChanges();
But that still returned the same error message. I also tested with other(new) properties that worked perfectly fine, deleted and retried the migrations, checked in my database for an error there but I am now unsure of the next step to take. There are no references to Email in my Context so is it something that I need to be initialising there?
Edit: I created another smaller scale project where I ran the exact same code and the email saved with no issues:
using (var db = new ETDbContext())
{
var newEmployee = new Employee
{
FirstName = "John",
LastName = "Smith",
DOB = new DateTime(1992, 09, 16),
Phone = "032166702"
};
db.People.Add(newEmployee);
var nc = new Customer
{
FirstName = "Jane",
LastName = "Doe",
DOB = new DateTime(1992, 09, 16),
Phone = "032166702",
Email = "customerEmail"
};
db.People.Add(nc);
db.SaveChanges();
}
I tried to add a Customer just to make sure everything worked but ran into the same problem! Anytime I would create an employee it would save no issues but with the customer it returned the same null reference error