确定属性是否是EF Core中的导航属性 [英] Determine if property is a Navigation Property in EF Core

查看:117
本文介绍了确定属性是否是EF Core中的导航属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个简单的变更跟踪器,以捕获对Sql Azure数据库的所有编辑(不幸的是,据我所知,Sql Azure本身不支持此功能)。

I'm building a simple change tracker to capture all the edits to a Sql Azure database (unfortunately, Sql Azure doesn't support this natively, so far as I can tell).

我正在浏览ChangeTracker()返回的已修改条目的列表:

I'm walking the list of modified entries returned by 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;
        }
    }
}

不幸的是,检索PropertyEntry信息导致属性爆炸-InvalidOperationException-当该属性是导航属性时,声称找不到该属性。

Unfortunately, retrieving the PropertyEntry info for a property blows up -- InvalidOperationException -- when the property is a navigation property, claiming the property can't be found.

我可以将代码包装在一个try / catch块...但是我很好奇是否还有其他方法可以从元数据中确定某个属性是导航属性还是相关属性。

I could just wrap the code in an try/catch block...but I'm curious if there's another way to determine, perhaps from metadata, that a property is a navigation or related property.

推荐答案

而不是使用反射

foreach (var prop in entry.Entity.GetType().GetTypeInfo().DeclaredProperties)

您可以使用 EntityEntry提供的元数据。元数据属性:

foreach (var prop in entry.Metadata.GetProperties())

请注意,<$ c $返回的 IEntityType c>元数据属性具有用于简单属性的单独方法( G etProperties 方法)和导航属性( GetNavigations 扩展方法)。

Note that the IEntityType returned by the Metadata property has separate methods for simple properties (GetProperties method) and navigation properties (GetNavigations extension method).

这篇关于确定属性是否是EF Core中的导航属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆