如何检索作为主键并在SQL Server中自动创建的键字段

时间:2017-03-01 20:44:50

标签: sql-server asp.net-mvc entity-framework

我要做的是在2个表CommunitiesCommunityTeams中创建记录。其中每个都有一个主键ID,在SQL Server中设置为Identity 1.1。现在,我想在Communities中捕获CommunityTeams作为外键的键,但我无法知道ID是什么。

这是我在ASP.NET MVC和实体框架中的代码:

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");
}

1 个答案:

答案 0 :(得分:1)

我承认您的Community实体中有CommunityTeam的导航属性。

team.CommunityId = 1;替换为team.Community = model;。然后只需添加团队实体,EF就会同时创建modelteam

db.CommunityTeams.Add(team);
db.SaveChanges();

您还可以在两个db.SaveChanges();来电之间拨打Add,将保存拆分为两部分。 第一次保存将创建Community实体,EF将自动填充您的主键,以便您可以在Team实体中使用它进行第二次保存。