EntityState.Modified without updating navigation property
我无法使用EntityState.Modified更新我的一个模型,因为它还尝试更新我的导航属性(我没有更改)。 我的控制器动作是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Rooms([Bind(Include ="ID,BedroomCount,BedroomsDescription,BathroomCount,BathroomsDescription")] Property property) { if (ModelState.IsValid) { //Modify property property.DateModified = DateTime.Now; property.Status = 1; db.Entry(property).State = EntityState.Modified; await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(property); } |
我的模型看起来像:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Property { public int ID { get; set; } public Int16 BedroomCount { get; set; } public string BedroomsDescription { get; set; } public Int16 BathroomCount { get; set; } public string BathroomsDescription { get; set; } public int CommunityID { get; set; } public int PropertyTypeID { get; set; } public virtual Community Community { get; set; } public virtual PropertyType PropertyType { get; set; } } |
正如你所看到的,我从我的viewModel绑定了一堆东西(浴室和卧室等),但我根本没有修改导航属性'Community',但每当我发布到这个动作方法时,我都会收到以下错误:
The UPDATE statement conflicted with the FOREIGN KEY constraint
"FK_dbo.Property_dbo.Community_CommunityID". The conflict occurred in
database"MyDatabase", table"dbo.Community", column 'ID'. The
statement has been terminated.
如何在不尝试更新外键的情况下更新此模型? 我无法在任何地方找到答案
嗨,请你试一下,我希望它会起作用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | [HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> Rooms([Bind(Include ="ID,BedroomCount,BedroomsDescription,BathroomCount,BathroomsDescription")] Property property) { if (ModelState.IsValid) { // try this read this entoity from context and update properties you need to update var dbproperty = db.Property.FirstOrDefault(x=>x.Id= property.Id); // handle null //Modify property dbproperty .DateModified = DateTime.Now; dbproperty .Status = 1; // assuming in your context class Properties is the name of table. db.Entry(dbproperty ).State = EntityState.Modified; await db.SaveChangesAsync(); return RedirectToAction("Index"); } return View(property); } |
将nav属性的状态也设置为
或者,在