【发布时间】:2016-12-09 10:44:46
【问题描述】:
这是我关于 SO 的第一个问题,尽管我长期以来一直将其用作资源。
首先,我知道关于这个主题有很多问题,我想我已经尝试了所有各种解决方案都无济于事,但可能我错过了一些基本的东西。
我在 asp.net MVC Web 应用程序上使用 EF4,不确定还有什么需要知道的,但如果有,请大喊。
据我所知,我只使用一个上下文“db”并且我没有使用“using”语句,所以我看不到上下文正在被处理,至少不是故意的,但我仍然保留遇到上面同样的错误。
情况是这样的,我有一个操作结果,它根据通过 ClaimGroup 连接到报告的“声明”创建一批连接到主模型“报告”的条目“报告部分”(见下文)。
因此,我的(简化的)类看起来像这样;
public partial class Claim
{
public Claim()
{
this.ReportSections = new HashSet<ReportSection>();
this.Reports = new HashSet<Reports>();
}
public int id {get; set;}
//other stuff
public virtual ICollection<Reports> Reports {get; set;}
public virtual ICollection<ReportSections> ReportSections {get; set;}
}
public partial class ClaimGroup
{
public ClaimGroup()
{
this.Claims = new HashSet<Claims>();
}
public int id {get; set;}
//other stuff
public virtual ICollection<Claims> Claims {get; set;}
public virtual ICollection<ReportSections> ReportSections {get; set;}
}
public partial class Report
{
public Report()
{
this.ReportSections = new HashSet<ReportSection>();
}
public int id {get; set;}
public int ClaimGroupId {get; set;}
//other stuff
public virtual ICollection<ReportSections> ReportSections {get; set;}
public virtual ClaimGroup ClaimGroup {get; set;}
}
public partial class ReportSection
{
public int id {get; set;}
public int ClaimId {get; set;}
public int ReportId {get; set;}
public int Position {get; set;}
//other stuff
public virtual Report Report {get; set;}
public virtual Claim Claim {get; set;}
}
[为免生疑问,我很高兴 Claims 和 ClaimGroups 之间的多对多关系可以正常工作,因为它在网站的其他区域也能正常工作。]
然后我的控制器有以下内容;
public ActionResult BuildSections(int id)
{
Report r = db.Reports.Find(id);
int i = 0;
foreach(Claim c in r.ClaimGroup.Claims)
{
r.ReportSections.Add(new ReportSection { Claim = c, Position = i});
i++;
}
db.SaveChanges();
}
这真的很烦人,因为它看起来并不复杂,但我显然做错了什么。
提前致谢。
Sy
编辑
保存回数据库时会触发错误,因此在此处的示例中它是在
db.SaveChanges();
但是,在我寻找解决方案的各种尝试中,我也尝试过
db.ReportSections.Add(new ReportSection {...});
并且在那一行发生了错误。
【问题讨论】:
-
当您尝试添加权限时会出现错误?尝试在变量上添加 ReportSection,如下所示:
var rs = new ReportSection{[..]}; db.ReportSections.Add(rs); -
Max - 感谢您指出我的问题中明显的遗漏。请参阅上面的编辑。当它被保存回数据库时,问题就发生了。
-
在添加新的
ReportSection时尝试提供ClaimId而不是整个Claim实例,如下所示:r.ReportSections.Add(new ReportSection { ClaimId = c.Id, Position = i}); -
@Diana 感谢您回来。我试过了,遗憾的是对结果没有任何影响。
-
您使用某种 DI 容器?你能发布控制器吗?
标签: c# asp.net asp.net-mvc entity-framework