EF5 How to get list of navigation properties for a domain object

后端 未结 4 719
一整个雨季
一整个雨季 2020-12-06 14:09

I\'m working on an EF 5 Code-First solution and I am trying to update an existing entity with a modified one using the Repository pattern:

    public void Up         


        
4条回答
  •  渐次进展
    2020-12-06 14:48

        public static T Clone(this T entity) where T : class
        {
            var type = entity.GetType();
            var clone = Activator.CreateInstance(type);
    
            var navigationProperties = type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty | BindingFlags.DeclaredOnly);
    
            foreach (var property in type.GetProperties(BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance | BindingFlags.SetProperty))
            {
                //if (property.Module.ScopeName == "EntityProxyModule") continue;
                if (navigationProperties.Contains(property)) continue;
    
                if (property.CanWrite)
                {
                    property.SetValue(clone, property.GetValue(entity, null), null);
                }
            }
    
            return (T)clone;
        }
    

    Only the navigation properties are defined directly on the dynamic proxy so using BindingFlags.DeclaredOnly will filter them out.

    The alternative (commented out) method differentiates the navigation properties using property.Module.ScopeName, for navigation properties this value will be "EntityProxyModule", whereas for the other properties this value will be the dll name of the project you defined the EF code first domain class in.

    I use this Clone method to clone EF code first domain objects ready for Json serialization (avoiding circular references), but the author's query as to how to get a list of navigation properties is contained within.

提交回复
热议问题