This seems so simple, yet I can't get it work. I have two tables, Organization and Season.
The Organization table can have an active season set, the season must be created with an Organization set.
Organization class (table)
public class Organization
{
public int ID { get; set; }
public string Name { get; set; }
[Display(Name = "Active Season")]
public int? ActiveSeasonID { get; set; }
public virtual Season ActiveSeason { get; set; }
}
Season class (table)
public class Season
{
public int ID { get; set; }
public int OrganizationID { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime EndDate { get; set; }
public string Name { get; set; }
public virtual Organization organization { get; set; }
}
Gives me this error:
Unable to determine the principal end of an association between the types 'ResultzSys.DAL.Organization' and 'ResultzSys.DAL.Season'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
So I have this to define the relationship between the two
modelBuilder.Entity<Organization>()
.HasOptional(s => s.ActiveSeason).WithRequired(d => d.organization);
but when I try to add a Season I get
Cannot insert explicit value for identity column in table 'Season' when IDENTITY_INSERT is set to OFF
Controller code that throws that error:
public async Task<ActionResult> Create([Bind(Include = "ID,OrganizationID,StartDate,EndDate,Name")] Season season)
{
if (ModelState.IsValid)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ResultzContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
season.OrganizationID = currentUser.OrganizationID;
db.Seasons.Add(season);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
}
I simply don't understand why it won't let me create the season record... Any hints are appreciated.
Thanks