I'm attempting to set up a composite primary key with the second key being the year.
I've set both in the table creation and the constructor to auto generate the field but I still get this error:
Cannot insert explicit value for identity column in table Volunteer when IDENTITY_INSERT is set to OFF.
All three parts to the code and setup are below.
[Table("Volunteer")]
public class Volunteer
{
[Key][Column(Order = 0)]
public int Id { get; set; }
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Last Name")]
public string LastName { get; set; }
[DisplayName("Team Mentored")]
public string TeamMentored { get; set; }
[Key][Column(Order = 1)] [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public DateTime Year { get; set; }
public string TableNumber { get; set; }
public int OfficeId { get; set; }
public string Image { get; set; }
}
CREATE TABLE [dbo].[Volunteer](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [nvarchar](255) NULL,
[LastName] [nvarchar](255) NULL,
[TeamMentored] [nvarchar](255) NULL,
[Year] [date] DEFAULT(getdate()) NOT NULL,
[TableNumber] [nvarchar](50) NULL,
[OfficeId] [int] NOT NULL,
[Image] [nvarchar](max) NULL
)
public ActionResult Create([Bind(Include = "FirstName,LastName,TeamMentored,TableNumber,OfficeId,Image")] Volunteer volunteer)
{
try
{
if (ModelState.IsValid)
{
db.Volunteers.Add(volunteer);
db.SaveChanges();
ModelState.Clear();
}
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
ModelState.AddModelError("", "DB Update Failed!");
}
return View();
}