你好,我有一个 MVC 应用程序,它有 CreatedDate 和 ModifiedDate 字段,
1.CreatedDate是用户创建模块的时间(任何条目)
2. ModifiedDate是用户编辑模块的时间
我有以下模型类
namespace MyForms.Models
{
public class Master
{
public int ID { get; set; }
public string ModuleName { get; set; }
public int CreatedBy { get; set; }
public DateTime ? CreatedDate { get; set; }
public int ModifyBy { get; set; }
public DateTime ModifyDate { get; set; }
public Boolean IsActive { get; set; }
public Boolean IsDeleted { get; set; }
// public virtual ICollection<Master> MasterModules { get; set; }
}
public class MyFormDemoContext : DbContext
{
public DbSet<Master> MasterForms { get; set;}
}
}
创建和编辑操作
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Master master)
{
try
{
using (MyFormDemoContext context = new MyFormDemoContext())
{
master.CreatedBy = 1;
master.CreatedDate = DateTime.Now;
var a = master.CreatedDate;
master.IsActive = true;
master.ModifyBy = 1;
master.ModifyDate = DateTime.Now;
master.IsDeleted = false;
context.MasterForms.Add(master);
context.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
}
}
public ActionResult Edit(int id)
{
using (MyFormDemoContext context = new MyFormDemoContext())
{
return View(context.MasterForms.Find(id));
}
}
//
// POST: /Home/Edit/5
[HttpPost]
public ActionResult Edit(int id, Master valpara)
{
try
{
using (MyFormDemoContext context = new MyFormDemoContext())
{
valpara.CreatedBy = 1;
valpara.CreatedDate = DateTime.Now;
valpara.IsActive = true;
valpara.ModifyBy = 1;
valpara.ModifyDate = DateTime.Now;
valpara.IsDeleted = false;
valpara.ModifyDate = DateTime.Now;
context.Entry(valpara).State = System.Data.EntityState.Modified;
context.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
return View();
} }
1.当前当我创建模块(实体)时,创建日期作为当前日期
2.当我编辑模块时,修改日期和创建日期相同
我的期望
我希望当我修改或编辑条目时,createdDate 保持不变,仅更新修改日期
当我编辑模块时,modifiedDate 和createdDate 相同
嗯,那是因为在你的Edit
您专门设置的操作CreatedDate
,删除这一行
valpara.CreatedDate = DateTime.Now
并且只有ModifiedDate
将会被更新。但是,更好的方法是将数据库配置为自动设置日期(例如,如果您使用 MSSQL,则将默认值设置为获取 UtcDate() http://msdn.microsoft.com/en-gb/library/ms178635.aspx)并让 EF 提取该值而不是在客户端设置它。
你需要设置DatabaseGeneratedOption.Identity
在该特定字段上,它告诉 EF DB 将生成该值。
仅供参考 - 你应该really考虑将日期存储为 UTC 而不是本地日期,即使用DateTime.UtcNow
而不是DateTime.Now
.
除上述内容外,在您的Edit
你实际上是重新创造每次都有一个新条目。如果你想modify现有记录,那么您需要先从数据库中提取该记录,例如
using (MyFormDemoContext context = new MyFormDemoContext())
{
var record = context.MasterForms.SingleOrDefault(x => x.ID == id);
if (record != null)
{
record.ModifyBy = 1;
record.ModifyDate = DateTime.UtcNow;
context.SaveChanges();
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)