如何自动使用外键填充表

时间:2012-03-25 15:17:43

标签: c# asp.net-mvc-3 asp.net-mvc-3-areas

我有以下代码:

var game = (from k in db.GamerTBLs
where k.UserName == User.Identity.Name
select k.GamerID).Single();
return View(game);

这是我的控制者:

[HttpPost]
public ActionResult Create(GameTBL gametbl)
{
    if (ModelState.IsValid)
    {
        db.GameTBLs.Add(gametbl);
        db.SaveChanges();
        return RedirectToAction("Index");  
    }

    var game = (from k in db.GamerTBLs where k.UserName == User.Identity.Name
        select k.GamerID).Single();

    return View(game);
}

我正在尝试将玩家ID填充到具有外键GamerIDFK的相关表Game。

如果您需要更多信息,请任何人可以了解一下,请告诉我

1 个答案:

答案 0 :(得分:0)

根据您提供的信息,我认为您的模型是这样的:

GamerTBL:

    public int GamerTBLId { get; set; }
    public string UserName { get; set; }
    public virtual ICollection<GameTBL> GameTBLs { get; set; }

GameTBL:

    public int GameTBLId { get; set; }
    public string GameName { get; set; }
    public int GamerIDFK { get; set; }

您的控制器应该是这样的:

[HttpPost]
public ActionResult Create(GameTBL gametbl)
{
    if (ModelState.IsValid)
    {
        //First you get the gamer, from GamerTBLs
        var gamer = db.GamerTBLs.Where(k => k.UserName == User.Identity.Name).SingleOrDefault();
        //Then you add the game to the games collection from gamers
        gamer.GameTBLs.Add(gametbl);
        db.SaveChanges();  
    }
    return RedirectToAction("Index");
}

实体框架抽象外键概念,您不必担心id或fk,只需将对象“添加”到对象集合即可。