- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在使用 Entity Framework 4.1,并且我有我的 DbContext Override SaveChanges 来审核属性更改。从“GetEntryValueInString”返回空值的代码。它的原因是“if (entry.Entity is EntityObject)”这个条件在所有情况下都失败了。如果我在评论条件时遇到另一个问题,例如 CurrentValues 和 OriginalValues 变得相同。
namespace mymodel
{
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
public partial class DbEntities : DbContext
{
public DbEntities ()
: base("name=DbEntities ")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<DBAudit> DBAudits { get; set; }
public string UserName { get; set; }
List<DBAudit> auditTrailList = new List<DBAudit>();
public enum AuditActions
{
I,
U,
D
}
public override int SaveChanges()
{
ChangeTracker.DetectChanges(); // Important!
ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;
IEnumerable<ObjectStateEntry> changes = ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified);
foreach (ObjectStateEntry stateEntryEntity in changes)
{
if (!stateEntryEntity.IsRelationship &&
stateEntryEntity.Entity != null &&
!(stateEntryEntity.Entity is DBAudit))
{//is a normal entry, not a relationship
DBAudit audit = this.AuditTrailFactory(stateEntryEntity, UserName);
auditTrailList.Add(audit);
}
}
if (auditTrailList.Count > 0)
{
foreach (var audit in auditTrailList)
{//add all audits
//this.AddToDBAudit(audit);
}
}
return base.SaveChanges();
}
private DBAudit AuditTrailFactory(ObjectStateEntry entry, string UserName)
{
DBAudit audit = new DBAudit();
audit.UpdateDate = DateTime.Now;
audit.TableName = entry.EntitySet.Name;
audit.UserId = UserName;
if (entry.State == EntityState.Added)
{//entry is Added
audit.NewData = GetEntryValueInString(entry, false);
audit.Actions = AuditActions.I.ToString();
}
else if (entry.State == EntityState.Deleted)
{//entry in deleted
audit.OldData = GetEntryValueInString(entry, true);
audit.Actions = AuditActions.D.ToString();
}
else
{//entry is modified
audit.OldData = GetEntryValueInString(entry, true);
audit.NewData = GetEntryValueInString(entry, false);
audit.Actions = AuditActions.U.ToString();
IEnumerable<string> modifiedProperties = entry.GetModifiedProperties();
//assing collection of mismatched Columns name as serialized string
//audit.TableName = XMLSerializationHelper.XmlSerialize(modifiedProperties.ToArray());
}
return audit;
}
private string GetEntryValueInString(ObjectStateEntry entry, bool isOrginal)
{
if (entry.Entity is EntityObject)
{
object target = CloneEntity((EntityObject)entry.Entity);
foreach (string propName in entry.GetModifiedProperties())
{
object setterValue = null;
if (isOrginal)
{
//Get orginal value
setterValue = entry.OriginalValues[propName];
}
else
{
//Get orginal value
setterValue = entry.CurrentValues[propName];
}
//Find property to update
PropertyInfo propInfo = target.GetType().GetProperty(propName);
//update property with orgibal value
if (setterValue == DBNull.Value)
{//
setterValue = null;
}
propInfo.SetValue(target, setterValue, null);
}//end foreach
XmlSerializer formatter = new XmlSerializer(target.GetType());
XDocument document = new XDocument();
using (XmlWriter xmlWriter = document.CreateWriter())
{
formatter.Serialize(xmlWriter, target);
}
return document.Root.ToString();
}
return null;
}
public EntityObject CloneEntity(EntityObject obj)
{
DataContractSerializer dcSer = new DataContractSerializer(obj.GetType());
MemoryStream memoryStream = new MemoryStream();
dcSer.WriteObject(memoryStream, obj);
memoryStream.Position = 0;
EntityObject newObject = (EntityObject)dcSer.ReadObject(memoryStream);
return newObject;
}
public DbSet<Area> Areas { get; set; }
public DbSet<Country> Countries { get; set; }
public DbSet<Event> Events { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<Holiday> Holidays { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Notification> Notifications { get; set; }
public DbSet<Receipt> Receipts { get; set; }
public DbSet<Report> Reports { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<State> States { get; set; }
public DbSet<Store> Stores { get; set; }
public DbSet<TimeZone> TimeZones { get; set; }
}
最佳答案
public partial class DbEntities
{
public enum AuditActions
{
I,
U,
D
}
public override int SaveChanges()
{
ChangeTracker.DetectChanges(); // Important!
ObjectContext ctx = ((IObjectContextAdapter)this).ObjectContext;
IEnumerable<ObjectStateEntry> changes = ctx.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Modified);
foreach (ObjectStateEntry stateEntryEntity in changes)
{
if (stateEntryEntity.EntitySet.Name != "MobileLoginDatas" && stateEntryEntity.EntitySet.Name != "SystemLookUps")//eliminate these tables
{
if (SessionData.userId != null && SessionData.userId != 0) //execute only after user login
{
if (!stateEntryEntity.IsRelationship &&
stateEntryEntity.Entity != null &&
!(stateEntryEntity.Entity is DBAudit))
{
DBAudit audit = new DBAudit();
audit.RevisionStamp = DateTime.Now;
audit.UserId = SessionData.userId;
audit.TableName = stateEntryEntity.EntitySet.Name;
audit.IPAddress = SessionData.clientIpAddress;
if (stateEntryEntity.State == EntityState.Added)
{//entry is Added
audit.Data = DictionaryToJsonConverter(GetEntryValueString(stateEntryEntity, false));
audit.Action = AuditActions.I.ToString();
}
else if (stateEntryEntity.State == EntityState.Deleted)
{//entry in deleted
audit.Data = DictionaryToJsonConverter(GetEntryValueString(stateEntryEntity, true));
audit.Action = AuditActions.D.ToString();
}
else
{//entry is modified
audit.Data = DictionaryToJsonConverter(GetEntryValueString(stateEntryEntity, false));
audit.Action = AuditActions.U.ToString();
}
this.Entry(audit).State = System.Data.EntityState.Added;
}
}
}
}
// }
return base.SaveChanges();
}
///convert the data to json
string DictionaryToJsonConverter(Dictionary<String, Object> dict)
{
var entries = dict.Select(d =>
string.Format("'{0}': {1}", d.Key, string.Join(",", d.Value)));
return "{" + string.Join(",", entries) + "}";
}
private Dictionary<string, object> GetEntryValueString(ObjectStateEntry entry, Boolean isOriginal)
{
var keyValues = new Dictionary<string, object>();
var values = (IDataRecord) null;
if (isOriginal)
{
values = entry.OriginalValues;
}
else
{
values = entry.CurrentValues;
}
for (int i = 0; i < values.FieldCount; i++)
{
keyValues.Add(values.GetName(i), values.GetValue(i));
}
return keyValues;
}
}
关于c# - DbDataRecord - entry.CurrentValues 和 entry.originalValues 相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20211041/
这个问题在这里已经有了答案: Entity Framework DbContext SaveChanges() OriginalValue Incorrect (6 个答案) 关闭 4 年前。 我正
我正在从网上找到的代码片段中编写审计跟踪。在调用我的 SaveChanges 函数时,我会遍历所有在上下文中注册的修改过的实体,并从它们的更改中构建日志条目。 foreach (DbEntityEnt
如何将ObjectStateEntry.OriginalValues转换为Entity?我认为我可以使用 ObjectContext.Translate 方法来做到这一点,但我必须传递 DataRea
我正在尝试覆盖 Entity Framework 的 SaveChanges() 方法来保存审计信息。我从以下内容开始: public override int SaveChanges() {
我正在编写一个 asp.net mvc4 应用程序,我正在使用 Entity Framework 5。我的每个实体都有像 EnteredBy、EnteredOn、LastModifiedBy 0)
下面是String类的构造函数 public String(String original) { int size = original.count; char[] originalValue = o
我正在尝试使用 EF 4.1 实现 AuditLog,方法是重写在以下位置讨论的 SaveChanges() 方法: http://jmdority.wordpress.com/2011/07/20/
我在 EF7/asp.Net Core 应用程序中遇到问题。在我的上下文中,我创建了一个保存方法: public int Save() { ChangeTracker.
我的代码看起来很简单: bool rv = false; var results = from user in Users where user.userName.Equals
我正在使用 Entity Framework 4.1,并且我有我的 DbContext Override SaveChanges 来审核属性更改。从“GetEntryValueInString”返回空
我在更新 EF Core 中的实体然后在表中记录这些更改时遇到了问题。使用的技术是: .NET 核心 2.2.0 EF 核心 2.2.3 所以,我想从数据库中获取一个实体,在前端对其进行编辑,然后在后
我对 Entity Framework 还很陌生。作为了解更多关于 EF 的入门者,我正在尝试按照 http://genericunitofworkandrepositories.codeplex.c
我有一个文档库站点,我想在编辑文档对象时发送一封包含更改摘要的电子邮件。 数据库交互是使用 DBContext 的 Code First Entities Framework 这是我目前所拥有的:
我有一个文档库站点,我想在编辑文档对象时发送一封包含更改摘要的电子邮件。 数据库交互是使用 DBContext 的 Code First Entities Framework 这是我目前所拥有的:
在字符串构造函数的代码中 - public String(String original) { int size = original.count; char[] originalVa
好吧,这个问题对我来说似乎非常奇怪。我有一个用于编辑和创建新文章的 View 。编辑现有文章非常有效,但是创建新文章会给我一个空引用异常(“对象引用未设置为对象的实例”)。 这是我的代码: //Ret
我是一名优秀的程序员,十分优秀!