【发布时间】:2012-04-27 13:05:23
【问题描述】:
我正在尝试更新模型,但收到错误“操作失败:无法更改关系,因为一个或多个外键属性不可为空。当对关系进行更改时,相关外键属性设置为空值。如果外键不支持空值,则必须定义新的关系,必须为外键属性分配另一个非空值,或者不相关的对象必须删除。”
根据我从The relationship could not be changed because one or more of the foreign-key properties is non-nullable 了解到的情况,问题可能在于 Entity Framework 如何处理我的虚拟 ICollection
但是,当使用脚手架存储库模式时,我不确定如何实现该解决方案。我是否必须编辑 Save() 方法 ParentObjectRepository 类?
其实我真的觉得一定有办法让EF明白这一点。我看不出 EF 团队是如何思考“可能没有人使用具有外键约束的对象集合,我们不支持”。
更新 添加代码
[HttpPost]
public ActionResult Edit(int id, FormCollection formCollection)
{
var eventRepository = new MagnetEventRepository();
var original = eventRepository.Find(id);
UpdateModel(original);
eventRepository.Save();
return RedirectToAction("Details", "Home", new { slug = original.Slug });
}
public void Save()
{
context.SaveChanges();
}
更多代码:
public class MagnetEvent
{
public virtual int Id { get; set; }
[Required]
public virtual string Name { get; set; }
[Required]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm}")]
[DataType(DataType.DateTime)]
public virtual DateTime? StartDate { get; set; }
public virtual string Description { get; set; }
[StringLength(100)]
public virtual string Slug { get; set; }
public virtual int MaximumCapacity { get; set; }
[DataType(DataType.Currency)]
public virtual int TicketPrice { get; set; }
public virtual int LocationId { get; set; }
public virtual Location Location { get; set; }
public virtual Collection<Ticket> Tickets { get; set; }
public virtual Collection<AttendeeInformationField> CaptureAttendeeInformationFields { get; set; }
public virtual int CustomerId { get; set; }
[Required]
public virtual CUSTOMER Customer { get; set; }
}
Save()-方法来自 MagnetEventRepository,它是从上面的类中搭建的。
另一个更新 我通过将 AttendeeInformationField 中的 MagnetEventId 更改为可为空的 int 成功消除了错误。检查数据库时,我可以确切地看到问题所在。
假设我有一个值为“E-mail”的 AttendeeInformationField。当我编辑我的 MagnetEvent 时,AttendeeInformationField 将 MagnetEventId 更新为 null,然后添加具有正确 MagnetEventId 和值的新帖子。
我非常希望更新 AttendeeInformationField 中的帖子。
【问题讨论】:
-
你能发布你的查询和更新代码吗?
-
当然,我更新了原帖。
标签: asp.net-mvc entity-framework repository-pattern entity-framework-migrations