What I am trying to do is create a record in 2 tables, Communities and CommunityTeams. Each of these have a primary key ID which is set as a Identity 1.1 in SQL Server. Now, I would like to capture the key of Communities as a foreign key in CommunityTeams, but I have no way of knowing what that ID is.
Here is my code in ASP.NET MVC and Entity Framework:
if (ModelState.IsValid)
{
// Community Info
model.CommunityType = Convert.ToInt32(fc["communityType"]);
model.ComunityName = fc["communityName"];
model.CommunityCity = fc["communityCity"];
model.CommunityState = fc["communityState"];
model.CommunityCounty = fc["communityCounty"];
model.Population = Convert.ToInt32(fc["communityPop"]);
// Save to Database
model.Active = true;
model.DateCreated = DateTime.Now;
model.CreatedBy = User.Identity.Name;
model.Application_Complete = true;
model.Application_Date = DateTime.Now;
model.Payment_Complete = true;
model.Payment_Date = DateTime.Now;
model.Renewal = true;
model.Renewal_Date = DateTime.Now;
team.TeamLeader = true;
team.Admin = true;
var user = User.Identity.Name;
team.UserName = user.ToString();
team.CommunityId = 1;
db.CommunityTeams.Add(team);
db.Communities.Add(model);
db.SaveChanges();
return RedirectToAction("Index", "Habitats");
}