I'm very new to Entity Framework, so I'm sure this is a schoolboy error. I've check a few links here on Stackoverflow such as this thread, which gave me some things to try, but this has not fixed the issue.
I have a SQL database with a "tblPerson". The Primary Key is "PersonID" and it is set as the Identity, with a Seed=1 (int).
I then have a C#\ASP.NET front-end that I'm building.
I have a Class for Person:
public class Person
{
[Key]
public Int64 PersonID { get; set; }
[Required]
[StringLength(10)]
[RegularExpression("^[A-Za-z0-9]{2,10}$")]
public string Name { get; set; }
public bool Active { get; set; }
}
I have a Data Access Layer class that then handles the writing to the database:
public class PersonDAL : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Person>().ToTable("tblPerson");
modelBuilder.Entity<Person>().Property(x => x.PersonID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
public DbSet<Person> People { get; set; }
}
As you can see, I am telling it that PersonID field should be a database-generated identity.
Here is my code inside the Controller that calls an "Add":
public ActionResult Add(Person obj) //Validation runs here
{
if (ModelState.IsValid)
{
PersonDAL personDAL = new PersonDAL();
personDAL.People.Add(obj);
personDAL.SaveChanges();
personDAL.Dispose();
obj = null;
return View("AddPerson", obj);
}
else
{
return View("AddPerson", obj);
}
}
"obj" is populated via the razor view, but it will have PersonID=null, however, when I instantiate the Data Access Layer, and try to Add and Save, I would expect this to work, however, I get the error:
"Cannot insert the value NULL into column 'PersonID' the column does not allow nulls."
Any tips would be gratefully appreciated.
UPDATE: It seems that in my PersonDAL Data Access Layer, this line never gets triggered: public DbSet<Person> People { get; set; }
So, I am not sure why the line on the Controller personDAL.People.Add(obj);
is failing to set it? (I can prove all this by pulling back People as a a List to the controller, and it's count is 0). Any ideas anyone?
UPDATE - SILLY ERROR!! - I somehow managed to uncheck "Identity" in the SQL table design for PersonID in tblPerson. NOW FIXED.