0

我面临下一个问题。我有一个带有模型的数据仓库

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

        }

但是,当我尝试保存数据时,我发现我并没有将实体保存在事实表中,它们也将级联保存在子表中作为Location, Contender.

我怎样才能解决我的问题?

4

2 回答 2

1

您必须从数据库加载实体位置和竞争者。否则它们将被插入其中。

于 2013-04-06T21:02:31.433 回答
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 属性应该是他事实类的一部分,形成外键关联

于 2013-04-06T22:53:01.043 回答