2013-04-06 26 views
0

我面临下一个问题。我有一个模型数据仓库实体框架4.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(); 
      } 

     } 

但是,当我尝试保存的数据得到,我不救enity只是事实表他们得到级联保存在子表中作为Location, Contender

我该如何解决我的问题?

回答

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

+0

在第一种情况下,我得到'Microsoft.Office.Tools.Common.Implementation.dll中出现'System.Reflection.TargetInvocationException'类型的第一次机会异常' – Ray 2013-04-07 10:08:11

+0

,这只是一个想法。我无法控制'Microsoft.Office'的依赖关系。 – 2013-04-07 11:11:00

1

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

+0

我应该生成子实体,例如'Location location = locations [random.Next(countLocations)];' – Ray 2013-04-06 21:08:37

+0

什么是位置? – tschmit007 2013-04-06 21:14:54

+0

'List locations = selectLocations(); int countLocations = locations.Count();'从db中选择 – Ray 2013-04-06 21:15:57