我遇到了下一个问题。我有一个带模型的数据仓库
public class GameResult
{
public int GameResultId { get; set; }
public virtual Competition Competition { get; set; }
public virtual CustomDate DateGame { get; set; }
public virtual Contender ContenderFirst { get; set; }
public virtual Contender ContenderSecond { get; set; }
public virtual Location Location { get; set; }
}
public class Competition
{
[Key]
public int CompetitionId { get; set; }
public string Name { get; set; }
//Lazy loading
public virtual KindSport KindSport { get; set; }
}
这样的事情
我为事实表GameResult
gameResult.Location = location;
gameResult.Competition = competition;
gameResult.ContenderFirst = firstContender;
gameResult.ContenderSecond = secondContender;
public void saveGameResult(GameResult gameResult)
{
using (var db = new GameContext())
{
db.GameResults.Add(gameResult);
db.SaveChanges();
}
}
但是当我尝试保存数据时,我不会在实际表格中保存enity,他们也会在子表格中将级联保存为Location, Contender
。
我如何解决我的问题?
答案 0 :(得分:1)
您必须从数据库加载实体位置和竞争者。否则它们将被插入其中。
答案 1 :(得分:1)
Add
将整个对象图标记为Added
。
这是一种解决方法:
public void saveGameResult(GameResult gameResult, .... more arguments ....)
{
using (var db = new GameContext())
{
db.GameResults.Add(gameResult);
gameResult.Location = location;
gameResult.Competition = competition;
gameResult.ContenderFirst = firstContender;
gameResult.ContenderSecond = secondContender;
db.SaveChanges();
}
}
但是你必须添加更多的参数。
更乏味的方法是将所有内容保持原样并将每个维度标记为UnChanged
:
db.GameResults.Add(gameResult);
Entry(gameResult.Location).State = EntityState.Unchanged;
...
另一种方法是仅设置Id
值:
gameResult.LocationId = location.LocationId;
... etc.
public void saveGameResult(GameResult gameResult)
{
... (original code)
但当然原始Id属性应该是他的事实类的一部分,形成foreign key assocations。