Reputation: 249
I am receiving the following error when trying to perform an insert:
Cannot insert the value NULL into column 'Request_Cat_ID', table 'dbo.Request_Categories'; column does not allow nulls. INSERT fails.
The reason this error is baffling to me is because I have a table setup very similarly where the key column is a string instead of an int. I can insert without a problem to that table. The insert is small and simple, so here's the breakdown:
Model:
[Table("Request_Categories")]
public class RequestCategory
{
[Key]
[Column("Request_Cat_ID")]
public int RequestCategoryID { get; set; }
[Column("Request_Category")]
public string RequestCategoryName { get; set; }
}
Viewmodel:
public class RequestCategoryViewModel
{
public IEnumerable<RequestCategory> RequestCategories { get; set; }
}
Controller method:
[HttpPost]
public JsonResult AddRequestCategory(RequestCategory model)
{
var foo = model.RequestCategoryID; //There is a value that appears here. It does have an int type.
db.RequestCategories.Add(model);
db.SaveChanges();
return Json("");
}
Where it is passed in from the view:
$.post('@Url.Action("AddRequestCategory", "Services", new { area = "services" })',
{
RequestCategoryID: form.currentTarget.RequestCategoryID.value,
RequestCategoryName: form.currentTarget.RequestCategoryName.value,
}, AddRow, "json");
Any advice or tips are welcome!
Upvotes: 1
Views: 797
Reputation: 46501
You should add the DatabaseGeneratedAttribute
to RequestCategoryID
since you don't want it to auto increment:
[Key]
[Column("Request_Cat_ID")]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[public int RequestCategoryID { get; set; }
Entity Framework auto increment int
primary keys by convention.
Upvotes: 2