C# 如何使用外键自动填充表
我有以下代码:C# 如何使用外键自动填充表,c#,asp.net-mvc-3,asp.net-mvc-3-areas,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.
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的相关桌面游戏
请任何人解释一下,如果您需要更多信息,请根据您提供的信息告诉我。我想您的模型是这样的:
[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");
}
GamerTBL:
public int GamerTBLId { get; set; }
public string UserName { get; set; }
public virtual ICollection<GameTBL> GameTBLs { 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,只需将对象“添加”到对象集合中即可。您的问题有点让人困惑,您能解释一下页面应该做什么吗?,您也可以发布您的模型…我在创建时遇到一个错误您是否可以提供任何其他支持这是错误:错误1'mvcapapplication1.Controllers.GameController.create(mvcapapplication1.models.GameTBL)“:并非所有代码路径都返回值C:\UsersMvcApplication1\MVCAPApplication1\Controllers\GameController.cs 46 29 MVCAPApplication1MY bad,返回RedirectToAction(“索引”);应该在if语句之外。。。我的答案现在更新了