Im using Entity Framework code first and have recently created a new Repo model/table called ImportantCases.
I have set up the configuration and model just like every other however when i get to this line in my code:
public int CreateImportantCase(ImportantCase newImportantCase)
{
_context.ImportantCases.Add(newImportantCase);
_context.SaveChanges(); // <--- here
return newImportantCase.ImportantId;
}
I am getting this error:
Cannot insert the value NULL into column 'ImportantId', table 'MyDatabase.dbo.ImportantCases'; column does not allow nulls. INSERT fails. The statement has been terminated.
My model/configuration look like this:
Model
public class ImportantCase
{
public int ImportantId { get; set; }
public int EvpId { get; set; }
public string Comment { get; set; }
public int CategoryId { get; set;}
}
EF Configuration
class ImportantCaseConfiguration : EntityTypeConfiguration<ImportantCase>
{
public ImportantCaseConfiguration()
{
HasKey(x => x.ImportantId);
}
}
Prior to calling the create method I am setting up the new ImportantCase
via the Post method from the view using a view model and model binding:
if (imp != null ) // already a record, so update
{
imp.Comment = modifiedExceptionPersonViewModel.Comment;
imp.CategoryId = int.Parse(modifiedExceptionPersonViewModel.SelectedCategory);
_service.UpdateImportantCase(imp);
}
if (imp == null) //no record so create
{
ImportantCase newImportantCase = new ImportantCase();
newImportantCase.Comment = modifiedExceptionPersonViewModel.Comment;
newImportantCase.CategoryId = int.Parse(modifiedExceptionPersonViewModel.SelectedCategory);
newImportantCase.EvpId = modifiedExceptionPersonViewModel.EvpId;
_service.CreateImportantCase(newImportantCase);
}
I've inspected the newImportantCase
object just before the SaveChanges
and it looks as I would expect, with the ImportantId
set to '0', usually EF will just create the ID once the write has completed.
One thing I have noticed however is the Identity Specification is set to No
when I view the Design of that table, all the other tables that EF has created are set to Yes
, what have I done differently?
note
EvpId
is the Id of the viewmodel which is being returned from the view, I've just rolled the category and comment properties into this viewmodel in order to deal with them separately in the controller.
edit
I have just realised that I stupidly set the ImportantId
to a string when I ran initially update-database
but then added a new migration to rectify this later on, not realising EF does not retrospectively sort out the identity specification, is there a way around this?