Ok, so this problem seems to have lots of different answers on SO - but I can't find a duplicate that solves my issue or makes it clear to me what the problem is. The problem arises when I try to insert/create and is a validation error on db.SaveChanges(). First of all, I was getting a "Model must have an id" message under validation in the debugger. Of course, first of all my id was a string which I figured out doesn't make sense after reading this.How to generate and auto increment Id with Entity Framework I then changed my id to an int and removed the [Key] data annotations as per the link solution above. I also updated the db. However, the id now shows as 0 and I get a validation error saying "Cannot insert the value NULL into column id in..." However, if I hard code an id the table is updated fine. Here is code.. any help appreciated. The model:
public class Model
{
//[Key]
//[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ModelId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
[Required]
[DataType(DataType.Time)]
public DateTime OpenTime { get; set; }
[Required]
[DataType(DataType.Time)]
public DateTime CloseTime { get; set; }
//Navigation property
public virtual ICollection<OtherModel> OtherModels { get; set; }
}
The controller:
// GET: Model/Create
public ActionResult Create()
{
return View();
}
// POST: Model/Create
[HttpPost]
public ActionResult Create(Model model)
{
try
{
db.Models.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View(model);
}
}