locked
How to find and access navigation properties? RRS feed

  • Question

  • Hi

    I've  created a base business class for my application which performs basic CRUD operations based on EF 4:

    public abstract class BusinessBase<T> where T : ObjectContext, new()
     {

    public virtual List<TEntity> GetByPredicate<TEntity>(Expression<Func<TEntity, bool>> predicate) where TEntity : EntityObject
                {
                    using (T objectContext = new T())
                    {
                       
                        ObjectSet<TEntity> objectSet = objectContext.CreateObjectSet<TEntity>();
                        objectSet.MergeOption = MergeOption.NoTracking;
                        return objectSet.Where(predicate).ToList();
                    }
                }

    GetPredicate methods works well to retrieve all entity objects of type TEntity. But I need to be able to fetch the related records as well. I also need to set the MergeOption property of all related entities to "NoTracking" for some reasons.

    Is there a general way to find and iterate through the Navigation Properties of an entity in EF 4?

     

    Thanks

    Monday, September 20, 2010 5:08 AM

Answers

  • Is there a general way to find and iterate through the Navigation Properties of an entity in EF 4?

     

    I don't know if it is the best way, but you can use reflection to get hold of all members that are an entity type or EntityCollection<T>. E.g.:

    Type t = typeof(SomeEntity);
    var navMembers = t.GetProperties()
      .Where(pt => pt.PropertyType.IsSubclassOf(typeof(System.Data.Objects.DataClasses.EntityObject))
        || (pt.PropertyType.IsGenericType
            && pt.PropertyType.GetGenericTypeDefinition().UnderlyingSystemType == typeof(System.Data.Objects.DataClasses.EntityCollection<>)));

     

     


     

     

       Cool tools for Linq-to-SQL and Entity Framework 4:
     huagati.com/dbmltools - Rule based class and property naming, Compare and Sync model <=> DB, Sync SSDL <=> CSDL (EF4)
     huagati.com/L2SProfiler - Query profiler for Linq-to-SQL and Entity Framework v4
    • Proposed as answer by KristoferA Tuesday, September 21, 2010 3:15 AM
    • Marked as answer by liurong luo Thursday, September 23, 2010 9:02 AM
    Monday, September 20, 2010 5:16 AM