我有以下代码:
//
// POST: /PlayRoundHole/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
try
{
DB db = new DB();
PlayRound playRound = new PlayRound();
playRound.PlayerID = Int64.Parse(Request.Form["Value"]);
playRound.TenantID = 1;
playRound.RoundID = Int64.Parse(Request.Form["RoundID"].ToString());
playRound.Score = 0;
var playRoundHoles = from prh in db.PlayRoundHoles.ToList()
from hl in db.Holes.ToList()
where prh.HoleID == hl.HoleID
where prh.PlayRoundID == Int64.Parse(Request.Form["RoundID"].ToString())
select new { prh.HoleID, hl.Sequence };
foreach(var a in playRoundHoles)
{
PlayRoundHole playRoundHole = new PlayRoundHole();
playRoundHole.HoleID = a.HoleID;
playRoundHole.Stroke = Byte.Parse(Request.Form["PlayRoundHoleID_" + a.Sequence].ToString());
playRound.PlayRoundHoles.Add(playRoundHole);
}
db.SubmitChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
根本没有错误但是我看不到正在保存的数据。有任何想法吗?无论如何要跟踪这个吗?
答案 0 :(得分:1)
由于您的新对象未链接到datacontext(db),因此不会保存任何内容。 如果您希望将新的PlayRound实例及其PlayRoundHole子项持久保存到数据库,则需要调用以下内容:
db.PlayRounds.InsertOnSubmit(playRound);
db.SubmitChanges();
在旁注中,以下查询从数据库中获取所有PlayRoundHoles和所有洞,然后然后在应用程序中过滤它们。
var playRoundHoles = from prh in db.PlayRoundHoles.ToList()
from hl in db.Holes.ToList()
where prh.HoleID == hl.HoleID
where prh.PlayRoundID == 42
select new { prh.HoleID, hl.Sequence };
你可能想要的是:
var playRoundHoles = from prh in db.PlayRoundHoles
from hl in db.Holes
where prh.HoleID == hl.HoleID
where prh.PlayRoundID == 42
select new { prh.HoleID, hl.Sequence };
这只会获取匹配的孔,而不是从两个表中获取完整的行,它只会获取HoleID和序列号。