【发布时间】:2013-01-25 21:42:24
【问题描述】:
我们正在使用 EF5,代码优先方法来构建我们正在构建的 MVC4 应用程序。我们正在尝试更新实体上的 1 个属性,但不断收到错误消息。下面是上下文创建的类的样子:
public partial class Room
{
public Room()
{
this.Address = new HashSet<Address>();
}
public int RoomID { get; set; }
public Nullable<int> AddressID { get; set; }
public Nullable<int> ProductVersionID { get; set; }
public string PhoneNumber { get; set; }
public string AltPhone { get; set; }
public string RoomName { get; set; }
public string Description { get; set; }
public string Comments { get; set; }
public string Notes { get; set; }
public virtual ICollection<Address> Address { get; set; }
}
这是视图的 ViewModel:
public class RoomDetailsViewModel
{
//public int RoomID { get; set; }
public string RoomName { get; set; }
public string PhoneNumber { get; set; }
public string AltPhone { get; set; }
public string Notes { get; set; }
public string StateCode { get; set; }
public string CountryName { get; set; }
public string ProductVersion { get; set; }
public int PVersionID { get; set; }
public List<SelectListItem> ProductVersions { get; set; }
public Room Room { get; set; }
}
这是“保存”时调用的控制器操作:
[HttpPost]
public virtual ActionResult UpdateRoom(RoomDetailsViewModel model)
{
var db = new DBContext();
bool b = ModelState.IsValid;
var rooms = db.Rooms;
var rm = rooms.Where(r => r.RoomID == model.Room.RoomID).Single();
//List<Address> address = db.Addresses.Where(a => a.AddressID == rm.AddressID).ToList<Address>();
rm.ProductVersionID = model.PVersionID;
//rm.Address = address;
db.Entry(rm).Property(r => r.ProductVersionID).IsModified = true;
//db.Entry(rm).State = System.Data.EntityState.Modified;
db.SaveChanges();
return View("RoomSaved", model);
}
此视图所做的只是显示数据并允许用户更改产品版本(从 SelectList 中),因此,在房间实体中,我们要更新的只是 ProductVersionID 属性,仅此而已。我们可以让数据正常显示,但是当我们点击“保存”时,我们会得到这个错误:
'System.Collections.Generic.List`1[[Models.Address, Web.Mobile.TestSite,版本=1.0.0.0,文化=中性, PublicKeyToken=null]]' 不能从值中设置或删除 'Models.Address' 类型的 EntityReference 的属性。
正如您在控制器操作中看到的那样,我们尝试了几种不同的方法,但似乎都产生了这个错误。我尝试使用地址填充 model.Room.Address 集合,但没有,但仍然出现此错误。
我阅读了this StackOverflow article 和this article as well,但都没有解决我的问题。
对此的任何帮助将不胜感激!
【问题讨论】:
-
我注意到您有 2 个绑定列表(房间和房间),它们的记录相同但值不同。
-
@DaveA rooms 是整个房间列表,但 rm 是一个单人房间(来自 list a list of Rooms (rooms))。我通常不这样做,但如果可以的话,我试图将错误缩小到特定的语句。
-
我明白你为什么这样做。但是我怀疑是否在保存时间可以/应该存在 2 个相同属性的绑定列表(在 1 种情况下是冲突值)
标签: asp.net-mvc-4 ef-code-first entity-framework-5