我有一個可選的外鍵,我試圖設置爲null。無論我嘗試過什麼,在SaveChanges()上,update語句都將外鍵設置爲以前的值而不是null。無法將外鍵設置爲空
簡體子類:
public class Child
{
[Key, Column(Order = 0), ScaffoldColumn(false)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[ForeignKey("Parent")]
public int? ParentId { get; set; }
public virtual Parent Parent { get; set; }
}
簡化的父類:
public class Parent
{
[Key, Column(Order = 0), ScaffoldColumn(false)]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public virtual ICollection<Child> Children { get; set; }
}
事情我已經嘗試:
- 加載子對象,並設置的ParentId空,並設置Parent to null
- 加載子對象並設置Pa rentId空並迫使實體狀態進行修改
- 加載子對象包括父對象,然後在設置這些值爲空並迫使實體狀態進行修改
- 負載父對象,那麼孩子對象和。從父對象中移除(子)
- 加載Parent對象,然後加載Child對象,然後從Parent中加載.Remove(child),並將Child.ParentId設置爲null並將Child.Parent設置爲null。
目前我有:
public void RemoveChildFromParent(int childId, int parentId)
{
Parent parent = _context.Parents.Include(x => x.Children).FirstOrDefault(u => u.Id == parentId);
Child child = parent.Children.SingleOrDefault(u => u.Id == childId);
parent.Children.Remove(child);
child.ParentId = null;
child.Parent = null;
child.StateOfEntity = StateOfEntity.Modified;
_context.ApplyStateChanges();
_context.SaveChanges();
}
在保存更改,SQL UPDATE語句仍然對子對象舊值上的ParentId和我得到這個錯誤:
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=The changes to the database were committed successfully, but an error occurred while updating the object context. The ObjectContext might be in an inconsistent state. Inner exception message: A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
Source=System.Data.Entity
StackTrace:
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
at Insight.DataLayer.InsightContext.SaveChanges()
at Insight.DataLayer.ChildRepository.RemoveChildFromParent(Int32 childId, Int32 parentId)
at Insight.BusinessLayer.ParentManager.RemoveChild(Int32 id, Int32 parentId)
at Insight.PresentationLayer.Controllers.ParentController.RemoveChild(Int32 id, Int32 parentId)
at lambda_method(Closure , ControllerBase , Object[])
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException:
此外,不知道它是否重要,但我有LazyLoadingEnabled = false和AutoDetectChangesEnabled = false。
直接運行查詢以清空外鍵時會發生什麼? – NotMe
@ChrisLively,對於延遲抱歉。它工作正常,手動運行命令或使用'DbContext.Database.ExecuteSqlCommand()',所以我可能會堅持。它似乎不太適合這種方法,但是在這個小問題上又花了一天的時間。 –