实体框架4.0与奇怪的数据保存 [英] Entity framework 4.0 strange with saving data
本文介绍了实体框架4.0与奇怪的数据保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我面临的下一个问题。我有一个模型数据仓库
I faced with the next problem. I have a data warehouse with model
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只是在事实表中得到它们的级联也保存在子表为位置,竞争者
。
我怎样才能解决我的问题?
How I can solve my problem?
推荐答案
添加
标记。整个对象图作为添加
Add
marks the whole object graph as 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();
}
}
但你必须增加更多的参数。
But then you have to add more arguments.
一个比较繁琐的方法是放弃一切事情是这样的,并标记每个维度持平
:
A more tedious way is to leave everything the way it is and mark each dimension as UnChanged
:
db.GameResults.Add(gameResult);
Entry(gameResult.Location).State = EntityState.Unchanged;
...
还有一种方法是将标识
只值:
gameResult.LocationId = location.LocationId;
... etc.
public void saveGameResult(GameResult gameResult)
{
... (original code)
不过那当然简单的标识属性应该是他的事实类,形成的外键关联设定的。
But then of course the primitive Id properties should be part of he fact class, forming foreign key assocations.
这篇关于实体框架4.0与奇怪的数据保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文