我无法使用EntityState.Modified更新我的某个模型,因为它还尝试更新我的导航属性(我没有更改)。我的控制器动作是:
[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);
}
我的模型看起来像是:
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绑定了一堆东西(浴室和卧室等),但我没有修改导航属性&#39;社区&#39;根本没有,但每当我发布此动作方法时,我都会收到以下错误:
UPDATE语句与FOREIGN KEY约束冲突 &#34; FK_dbo.Property_dbo.Community_CommunityID&#34 ;.冲突发生在 数据库&#34; MyDatabase&#34;,表&#34; dbo.Community&#34;,列&#39; ID&#39;。该 声明已被终止。
如果不尝试更新外键,我该如何更新此模型?我无法在任何地方找到答案
答案 0 :(得分:1)
嗨,请你试一试,我希望它能奏效。
[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);
}
答案 1 :(得分:0)
将导航属性的状态也设置为EntityState.Unchanged
或EntityState.Modified
。
或者,在db.Entry(property).State = EntityState.Modified;
之前将nav属性设置为null。