问题描述
我有一个文档库网站,并希望在编辑文档对象时发送电子邮件,其中包含更改的摘要。
I have a document library site and would like to send an email when a document object is edited, containing a summary of the changes.
数据库交互是代码使用DBContext的第一个实体框架
The database interaction is Code First Entities Framework using DBContext
这是我迄今为止所做的:
Here is what I have so far:
[HttpPost]
public ActionResult Edit(Document document, bool sendEmail, string commentsTextBox)
{
if (ModelState.IsValid)
{
docsDB.Entry(document).State = EntityState.Modified;
foreach (string propertyName in docsDB.Entry(document).OriginalValues.PropertyNames)
{
var OriginalValue = docsDB.Entry(document).OriginalValues.GetValue<object>(propertyName);
var NewValue = docsDB.Entry(document).CurrentValues.GetValue<object>(propertyName);
if (!OriginalValue.Equals(NewValue))
{
//capture the changes
}
}
docsDB.SaveChanges();
if (sendEmail)
{
//sends email
}
return RedirectToAction("Index");
}
然而,OriginalValue和NewValue总是相同的 -
However, OriginalValue and NewValue are always the same -- the values of the update.
有没有什么办法,比如写入文件的东西比较麻烦,在POST之前捕获文档的状态?
Is there any way, short of something hacky like writing to a file, to capture the state of the document before the POST?
推荐答案
要将更新的属性与数据库中的值进行比较,必须从数据库重新加载文档。您可以这样尝试:
For the comparison of the updated properties with the values in the database you must reload the document from the database. You can try it this way:
[HttpPost]
public ActionResult Edit(Document document, bool sendEmail,
string commentsTextBox)
{
if (ModelState.IsValid)
{
var documentInDB = docsDB.Documents.Single(d => d.Id == document.Id);
docsDB.Entry(documentInDB).CurrentValues.SetValues(document);
foreach (string propertyName in docsDB.Entry(documentInDB)
.OriginalValues.PropertyNames)
{
var OriginalValue = docsDB.Entry(documentInDB)
.OriginalValues.GetValue<object>(propertyName);
var NewValue = docsDB.Entry(documentInDB)
.CurrentValues.GetValue<object>(propertyName);
if (!OriginalValue.Equals(NewValue))
{
//capture the changes
}
}
docsDB.SaveChanges();
if (sendEmail)
{
//sends email
}
return RedirectToAction("Index");
}
// ...
}
这篇关于使用DBContext Entry.OriginalValues和Entry.NewValues记录更改的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!