简体   繁体   中英

How to know whether a property stored in DbEntityEntry is a property`?

In Entity Framework 6 within an DbEntityEntry certain information can be retrieved by calling Property . However, this fails with an ArgumentException when the property is not a property but a collection or reference. Than other functions must be used.

How can I know which function to call? That is, how can I know of what type (simple property, complex property, reference, collection) the property is?

For DbEntityEntry see https://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbentityentry%28v=vs.113%29.aspx

I am using Entity Framework 6.1.3 in Visual Studio 2013.

I have find how to get if the navigation property is collection type or not. For this, we need to get BuiltInTypeKind of the property.

I am using this code for getting all navigation properties of the entity:

var entitySetElementType = ((IObjectContextAdapter)context).ObjectContext.CreateObjectSet<TEntity>().EntitySet.ElementType;
var navProperties = entitySetElementType.NavigationProperties;

Then, we can know if th navigation property is collection or not:

foreach (var navigationProperty in entiySetElementType.NavigationProperties)
{
      var builtInType = navigationProperty.TypeUsage.EdmType.BuiltInTypeKind;
      var isCollection = builtInType == System.Data.Metadata.Edm.BuiltInTypeKind.CollectionKind
                      || builtInType == System.Data.Metadata.Edm.BuiltInTypeKind.CollectionType;
}

UPDATE

Since EF has been moved to a separate assembly & namespace, the System.Data.Metadata.Edm.BuiltInTypeKind.CollectionKind in above code should be changed to System.Data.Entity.Core.Metadata.Edm.BuiltInTypeKind.CollectionKind .

DbEntityEntry.Member(string)返回一个DbMemberEntry ,您可以使用(memberEntry is DbPropertyEntry)进行检查(memberEntry is DbPropertyEntry)

One of the steps is to dig through those dynamic proxies. I do it with:

    if ( targetType.BaseType != null
        && targetType.Namespace == "System.Data.Entity.DynamicProxies" )
    {
        targetType = targetType.BaseType;
    }

Not really clean, but does the job.

Update

Based on jjj's answer, I came up with the following method:

        private bool IsSimpleProperty( string propertyName, DbEntityEntry entry )
        {
            DbMemberEntry memberEntry = entry.Member( propertyName );

            return memberEntry is DbPropertyEntry;
        }

By varying the is expression, you could check for all types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM