【发布时间】:2014-08-06 00:17:23
【问题描述】:
从记录中删除外键值时,我无法将记录保存到 SQL Server 数据库。
例如,我有一个现有的 BatchDetail 记录,主键 BatchDetailID = 10。它与现有的 RunDetail 记录相关联,主键 RunDetailID = 20,外键 BatchDetailID = 10。我想通过将 RunDetails.BatchDetailID 设置为 null 来解除 RunDetail 与 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();
}
}
}
所有其他记录更新,包括将外键值更改为另一个,都可以正常工作。
谁能看出我的缺点是什么?
【问题讨论】:
-
BatchDetailID 不能为空,你怎么能这样设置
runDetail.BatchDetailID = null;?? -
@YuliamChandra 谢谢,这是我在转录原始代码时犯的一个错误。我现在已经在上面更新以反映
Nullable<int>。
标签: c# entity-framework crud