C# 是否有更好的方法从DBContext修改的条目重建实体类
目前,我正在使用以下代码从DBContext修改的条目重新构造实体 假设我的实体类是C# 是否有更好的方法从DBContext修改的条目重建实体类,c#,entity-framework,C#,Entity Framework,目前,我正在使用以下代码从DBContext修改的条目重新构造实体 假设我的实体类是 public partial class JournalEntryCode : IAuditColumns { public JournalEntryCode() { this.JournalEntries = new HashSet<JournalEntry>(); } public int journal_entry_code_pk { get;
public partial class JournalEntryCode : IAuditColumns
{
public JournalEntryCode()
{
this.JournalEntries = new HashSet<JournalEntry>();
}
public int journal_entry_code_pk { get; set; }
public string journal_entry_code { get; set; }
public System.DateTime tstamp { get; set; }
public virtual ICollection<JournalEntry> JournalEntries { get; set; }
}
public部分类JournalEntryCode:IAuditColumns
{
PublicJournalEntryCode()
{
this.JournalEntries=new HashSet();
}
公共整数日记帐项目代码主键{get;set;}
公共字符串日志\条目\代码{get;set;}
public System.DateTime tstamp{get;set;}
公共虚拟ICollection日志{get;set;}
}
目前,我通过以下例行程序来实现这个问题的解决方案(它是有效的),但我必须相信有一种更优雅的方法来实现这一点
private List<JournalEntryCode> GetListModifedEntities()
{
List<JournalEntryCode> listJournalEntryCodes = new List<JournalEntryCode>();
var changeInfo = Context.ChangeTracker.Entries()
.Where(t => t.State == EntityState.Modified)
.Select(t => new
{
Current = t.CurrentValues.PropertyNames.ToDictionary(pn => pn, pn => t.CurrentValues[pn]),
});
foreach (var change in changeInfo)
{
JournalEntryCode jec = new JournalEntryCode();
foreach (var pair in change.Current)
{
switch (pair.Key)
{
case "journal_entry_code_pk":
jec.journal_entry_code_pk = (int)pair.Value;
break;
case "journal_entry_code":
jec.journal_entry_code = (string)pair.Value;
break;
case "tstamp":
jec.tstamp = (DateTime)pair.Value;
break;
}
}
listJournalEntryCodes.Add(jec);
}
return listJournalEntryCodes;
}
私有列表getListModifiedEntities()
{
List listJournalEntryCodes=新列表();
var changeInfo=Context.ChangeTracker.Entries()
.Where(t=>t.State==EntityState.Modified)
.选择(t=>new
{
Current=t.CurrentValues.PropertyNames.ToDictionary(pn=>pn,pn=>t.CurrentValues[pn]),
});
foreach(变更信息中的var变更)
{
JournalEntryCode jec=新的JournalEntryCode();
foreach(变化中的var对。当前)
{
开关(配对钥匙)
{
案例“日记账分录代码主键”:
jec.journal\u entry\u code\u pk=(int)pair.Value;
打破
案例“日记账分录代码”:
jec.journal\u entry\u code=(string)pair.Value;
打破
案例“tstamp”:
jec.tstamp=(DateTime)pair.Value;
打破
}
}
listJournalEntryCodes.Add(jec);
}
返回listJournalEntryCodes;
}
DbPropertyValues
有一种方法,您可以使用该方法从实体的当前值创建新的分离对象:
return Context.ChangeTracker.Entries<JournalEntryCode>()
.Where(e => e.State == EntityState.Modified)
.Select(e => e.CurrentValues.ToObject())
.Cast<JournalEntryCode>()
.ToList();
返回Context.ChangeTracker.Entries()
.Where(e=>e.State==EntityState.Modified)
.选择(e=>e.CurrentValues.ToObject())
.Cast()
.ToList();
请尝试以下操作。