【发布时间】:2017-09-15 01:48:58
【问题描述】:
我不知道我是否遗漏了什么......无论如何:
例如,您可以看到,属性为“HomeTeam”=“Forest Green Rovers”的对象的状态为“Unchanged”。无论如何,就我而言,所有实体都是“不变的”。所以,如果我是正确的,saveChanges 不应该尝试将它们插入到我的表中,但这就是它正在发生的事情:
主键已被违反,但 EF 不应该尝试添加此记录(属性 HomeTeam = 'Forest Green Rovers' 的记录),因为它是“未更改”,对吧?
EF 为什么要这样做?
实体:
{
using System;
using System.Collections.Generic;
public partial class MatchInfo
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public MatchInfo()
{
this.Sport = "Soccer";
this.OddsInfoes1X2 = new HashSet<OddsInfo1X2>();
this.Odds1X2Movements = new HashSet<OddsMovement>();
this.OddsInfoOverUnders = new HashSet<OddsInfoOverUnder>();
this.OddsMovementOverUnders = new HashSet<OddsMovementOverUnder>();
this.HistoryResults = new HashSet<HistoryResult>();
}
public string League { get; set; }
public System.DateTime Date { get; set; }
public string HomeTeam { get; set; }
public string AwayTeam { get; set; }
public string FinalScore { get; set; }
public string Sport { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<OddsInfo1X2> OddsInfoes1X2 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<OddsMovement> Odds1X2Movements { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<OddsInfoOverUnder> OddsInfoOverUnders { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<OddsMovementOverUnder> OddsMovementOverUnders { get; set; }
public virtual TeamsStatFinal TeamsStatFinal { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<HistoryResult> HistoryResults { get; set; }
}
}
更多信息:
foreach (something){
/*iterating on a web page and where I build the object oMatchInfo */
if (oMatchInfo != null)
{
oMatchInfoTemp = (from m in context.MatchInfoes where m.HomeTeam == oMatchInfo.HomeTeam && m.AwayTeam == oMatchInfo.AwayTeam && m.Date == oMatchInfo.Date select m).FirstOrDefault<MatchInfo>();
if (oMatchInfoTemp == null)
{
context.MatchInfoes.Add(oMatchInfo);
}
else
{
context.OddsInfoes1X2.AddRange(oMatchInfo.OddsInfoes1X2);
}
}
}
/* here there is the context.saveChanges() - the context is the same */
操作。我发现了我的错误,这真的很愚蠢:-( 在 for 内部的相关函数中有一些未注释的代码,我在其中添加实体而不检查 PK 约束。 状态“未改变”(第一张图片)让我感到困惑,我一直专注于... 对不起:-)
【问题讨论】:
-
是所有代码吗?你能把这个类也包括在实体中吗
-
请添加另一个定义密钥的
partial class MatchInfo。您的问题是该部分中的Edit: That's the part where I check the primary key before adding in the context:,请添加调用位置。 -
就像我说的添加!你在哪里打电话
if (oMatchInfo != null) {代码....
标签: c# entity-framework