这是当前的基本代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Registration registration)
{
if (ModelState.IsValid)
{
db.Entry(registration).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(registration);
}
我在注册表中有大约15个字段,我怎么只想更新"日期"字段,我在这里收到的对象是"注册"只有日期值,但当前代码更新所有条目,我想要的只是更新"日期"我已经进入"注册"
的领域非常感谢帮助:)
答案 0 :(得分:6)
将其附加到Unchanged
状态的上下文,并仅将Date
设置为已修改。
if (ModelState.IsValid)
{
db.Registrations.Attach(registration); // attach in the Unchanged state
db.Entry(registration).Property(r => r.Date).IsModified = true;
// Date field is set to Modified (entity is now Modified as well)
db.SaveChanges();
return RedirectToAction("Index");
}
你说传入的实体只填充了Date
,希望也有一个Id。 :)
答案 1 :(得分:1)
试试这个
if (ModelState.IsValid)
{
db.Entry(registration).State = EntityState.Modified;
db.Entry(registration).Property(x => x.Name).IsModified = false; //Add fields which you don't want to modify
db.SaveChanges();
return RedirectToAction("Index");
}
根据此post 中的答案,更新
var excluded = new[] { "property1", "property2" };
var entry = context.Entry(obj);
entry.State = EntityState.Modified;
foreach (var name in excluded)
{
entry.Property(name).IsModified = false;
}
答案 2 :(得分:0)
Registration registor =db.Registration.First(f=>RegistrationId==RegistrationId);
registor.Date = registration.Date;
db.SaveChanges();
将此用于单个记录更新,我假设注册在您的注册表中。