当我在一个实体上使用GetById()然后将子实体的集合设置为来自MVC视图的新列表时,我收到此错误.
操作失败:无法更改关系,因为一个或多个外键属性不可为空.当对关系进行更改时,相关的外键属性将设置为空值.如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象.
我不太明白这一行:
由于一个或多个外键属性不可为空,因此无法更改关系.
为什么要更改2个实体之间的关系?它应该在整个应用程序的整个生命周期内保持不变.
发生异常的代码很简单,即将集合中已修改的子类分配给现有父类.这有望满足删除子类,添加新类和修改的需要.我原以为Entity Framework会处理这个问题.
代码行可以提炼为:
var thisParent = _repo.GetById(1);
thisParent.ChildItems = modifiedParent.ChildItems();
_repo.Save();
Run Code Online (Sandbox Code Playgroud) 如果我尝试删除"子"行,我总是会遇到异常.这是一个片段:
using (var context = new CompanyContext())
{
ItemType itemType = context.ItemTypes.FirstOrDefault(i => i.Name == "ServerType");
ItemTypeItem itemTypeItem = itemType.Items.FirstOrDefault(i => i.Name == "DatabaseServer");
itemType.Items.Remove(itemTypeItem);
context.SaveChanges(); <=== exception!
}
Run Code Online (Sandbox Code Playgroud)
该SaveChanges()方法抛出以下异常.
"由于一个或多个外键属性不可为空,因此无法更改关系.当对关系进行更改时,相关的外键属性将设置为空值.如果外键是如果不支持空值,则必须定义新关系,必须为foreign-key属性分配另一个非空值,或者必须删除不相关的对象."
实体配置
public class ItemTypeConfiguration : NamedEntityConfiguration<ItemType>
{
public ConfigurationColumn ParentIDColumn;
public ConfigurationColumn ValidationPatternColumn;
public ItemTypeConfiguration() : base()
{
ParentIDColumn = new ConfigurationColumn() { Name = "ParentID", Ordinal = base.LastOrdinalPosition + 1 };
ValidationPatternColumn = new ConfigurationColumn() { Name = "ValidationPattern", Length = 1024, Ordinal=base.LastOrdinalPosition + 2};
this.Property(t …Run Code Online (Sandbox Code Playgroud) 单击保存(更新)我的表单后出现此错误:
由于一个或多个外键属性不可为空,因此无法更改关系.当对关系进行更改时,相关的外键属性将设置为空值.如果外键不支持空值,则必须定义新关系,必须为外键属性分配另一个非空值,或者必须删除不相关的对象.
这是我的控制器(案例"保存"在swich couse问题):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(UserModel userModel, string act = null, int idx = 0)
{
using (var dbContext = new userDbEntities())
{
if (userModel.User == null)
{
userModel.User = new UsersTable();
}
var newUser = userModel.User.userID == 0;
userModel.CustomTypes = dbContext.CustomTypes.ToList();
switch (act)
{
case "addcustom":
userModel.User.CustomerTables.Add(new CustomerTable
{
CustomType = new CustomType(),
UsersTable = userModel.User
});
break;
case "deletecustom":
userModel.User.CustomerTables.RemoveAt(idx);
break;
case "save":
foreach (var customer in userModel.User.CustomerTables)
{
customer.CustomType = dbContext.CustomTypes.Find(customer.CustomType.Id_NewCustomerType);
}
var dbUser …Run Code Online (Sandbox Code Playgroud)