从记录中删除外键值时,我无法将记录保存到SQL Server数据库中。
例如,我有一个主键BatchDetailID = 10的现有BatchDetail记录,并且它与一个主键RunDetailID = 20,外键BatchDetailID = 10的现有RunDetail记录关联。我想取消关联RunDetail通过将RunDetails.BatchDetailID设置为null可以从BatchDetail中获取。
这是错误消息:
发生引用完整性约束冲突:关系一端的'BatchDetail.BatchDetailID'的属性值与另一端的'RunDetail.BatchDetailID'的属性值不匹配。
这是我的课程定义:
public class RunDetail
{
public int RunDetailID { get; set; }
public Nullable<int> BatchDetailID { get; set; }
public virtual BatchDetail BatchDetail { get; set; }
}
public class BatchDetail
{
public int BatchDetailID { get; set; }
public virtual ICollection<RunDetail> RunDetails { get; set; }
}
当一个RunDetail
对象具有一个BatchDetailID
值,并且我尝试将其设置回null时,会发生错误:
public class MyController : Controller
{
private ISvr _myService;
public ISvr MyService
{
get { return _myService ?? (_myService = new MyHandler().GetMyService()); }
set
{
_myService = value;
}
}
public void UpdateBatch(int id)
{
foreach (var batchDetail in MyService.ReadBatchDetails(id))
{
var runDetail = MyService.ReadRunDetail(batchDetail.RunDetailID);
runDetail.BatchDetailID = null;
runDetail.BatchDetail = null; // I have tried with, and without, this line
MyService.UpdateRun(runDetail );
}
}
}
public class MyHandler
{
public ISvr GetMyService()
{
return new MySvr();
}
}
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall)]
public class MySvr : IMySvr
{
public void UpdateRun(RunDetail runDetail)
{
using (var myEntities = new MyEntities())
{
myEntities.RunDetails.Attach(runDetail); // This is where the exception hits
myEntities.Entry(runDetail).State = EntityState.Modified;
myEntities.SaveChanges();
}
}
}
所有其他记录更新,包括将外键值更改为另一个,都可以正常工作。
谁能看到我的缺点?
问题的根源是我未在问题中包括的一种方法。当我检索父BatchDetail
记录时,我包括了“ RunDetails”记录:
public List<BatchDetail> ReadBatchDetails(int id)
{
using (var myEntities = new MyEntities())
{
return myEntities.BatchDetails
.Include("RunDetails") // This is the problem
.AsNoTracking().ToList();
}
}
通过创建一个not的新方法Include("RunDetails")
,该问题得以解决:
public List<BatchDetail> ReadBatchDetailsWithoutRunDetails(int id)
{
using (var myEntities = new MyEntities())
{
return myEntities.BatchDetails.AsNoTracking().ToList();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句