Mar*_*ert 3 c# entity-framework-core
我正在构建一个简单的更改跟踪器来捕获对 Sql Azure 数据库的所有编辑(不幸的是,据我所知,Sql Azure 本身不支持此功能)。
我正在遍历 ChangeTracker() 返回的修改条目列表:
foreach( EntityEntry entry in _context.ChangeTracker.Entries()
.Where( e => e.State == EntityState.Modified ) )
{
foreach( var prop in entry.Entity
.GetType()
.GetTypeInfo()
.DeclaredProperties )
{
// this line blows up on navigation properties
PropertyEntry propEntry = entry.Property( prop.Name );
if( propEntry.IsModified )
{
var curValue = entry.Property( prop.Name ).CurrentValue;
var origValue = entry.Property( prop.Name ).OriginalValue;
}
}
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,检索属性的 PropertyEntry 信息会失败 - InvalidOperationException - 当该属性是导航属性时,声称无法找到该属性。
我可以将代码包装在 try/catch 块中...但我很好奇是否有另一种方法可以(也许从元数据)确定属性是导航或相关属性。
而不是使用反射
foreach (var prop in entry.Entity.GetType().GetTypeInfo().DeclaredProperties)
Run Code Online (Sandbox Code Playgroud)
您可以使用该属性提供的元数据EntityEntry.Metadata:
foreach (var prop in entry.Metadata.GetProperties())
Run Code Online (Sandbox Code Playgroud)
请注意,IEntityType属性返回的简单属性(方法)和导航属性(扩展方法)Metadata具有单独的方法。GetPropertiesGetNavigations
| 归档时间: |
|
| 查看次数: |
2125 次 |
| 最近记录: |