我的存储库中有一个更新功能,用于更新TerminalCertification实体。但是这个实体与另一个阶级(GomrokJustification)有许多关系 我的更新功能正确更新实体,但在相关实体上没有任何内容。 我的更新功能如下:
public void UpdateTerminalCertification(TerminalCertification terminalCertification)
{
var lastCertification =
db.terminalCertifications.Include("TimeInfo").Include("GomrokJustifications").Where(item=>item.TerminalCertificationID==terminalCertification.TerminalCertificationID).ToList();
if (lastCertification.Count==0)
throw new TerminalCertificationNotFoundException(terminalCertification);
terminalCertification.TimeInfo = lastCertification[0].TimeInfo;
((IObjectContextAdapter)db).ObjectContext.Detach(lastCertification[0]);
((IObjectContextAdapter)db).ObjectContext.AttachTo("terminalCertifications", terminalCertification);
foreach (var gomrokJustification in terminalCertification.GomrokJustifications)
{
((IObjectContextAdapter)db).ObjectContext.AttachTo("gomrokJustifications", gomrokJustification);
((IObjectContextAdapter)db).ObjectContext.ObjectStateManager.ChangeObjectState(gomrokJustification, EntityState.Modified);
}
((IObjectContextAdapter) db).ObjectContext.ObjectStateManager.ChangeObjectState(terminalCertification,EntityState.Modified);
}
我的TerminalCetrification有一个GomrokJustifications列表,之前由一些实体填充。我希望那些最后的实体被新的实体取代。但这不会发生。 有没有人有任何想法?
答案 0 :(得分:1)
而不是这样做:
var lastCertification = db.terminalCertifications
.Include("TimeInfo")
.Include("GomrokJustifications")
.Where(item=>item.TerminalCertificationID==terminalCertification.TerminalCertificationID)
.ToList();
if (lastCertification.Count==0)
throw new TerminalCertificationNotFoundException(terminalCertification);
你可以这样做:
var lastCertification = db.terminalCertifications
.Include("TimeInfo")
.Include("GomrokJustifications")
.Where(item=>item.TerminalCertificationID==terminalCertification.TerminalCertificationID)
.FirstOrDefault();
if (lastCertification == null)
throw new TerminalCertificationNotFoundException(terminalCertification);
如果集合中没有元素,则首先抛出异常,因此如果您不关心terminalcertificationnotfoundexception,您甚至可以删除该自定义异常。您的逻辑似乎甚至假设返回列表中只有一个元素,因此您甚至可以使用Single()。与调用tolist然后检索第一个项目相比,这表达了你想要实现的更多。
我们需要更多信息来帮助您。