Question

I turned off Lazy Load in my application:

this.Configuration.LazyLoadingEnabled = false;

My self-reference entity type is:

 public partial class Okved : BaseEntity
 {
        public Okved()
        {
            this.ChildOkveds = new HashSet<Okved>();
            this.TitleOkved = new HashSet<TitleOkved>();
        }

        public Nullable<int> OkvedId { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Okved> ChildOkveds { get; set; }
        public virtual Okved ParentOkved { get; set; }
        public virtual ICollection<TitleOkved> TitleOkved { get; set; }
  }

But in my Dao method, which return all entities each entity has child entities, but it shouldn't... :

 public virtual List<T> All(Expression<Func<T, object>> include = null)
 {
        List<T> result;
        var query = DbConnection.BaseEntitySet.OfType<T>();

        if (include != null)
            query = query.Include(include);

        result = query.ToList();

        return result;
  }

enter image description here

So, how can I turn off including self-referencing entities in my query? In other cases(when entity got reference on other type entity) eager loading works fine.

Was it helpful?

Solution

With this statement

DbConnection.BaseEntitySet.OfType<T>();

you are retrieving all entities of certain type, say Okved.

Since Okved has navigation properties of the same type, or collection of this type, all of them will be initialized as well, since this is how the context tracks loaded entities. After certain entity is materialized, all other entities that are loaded in context are updated so that their navigation properties will be set if they point at newly created entity.

To work this out, adjust your Dao method to not include information about properties you don't want to. Mind you if you set entity property to null, it will be considered as entity update, and will be processed if you call SaveChanges of your entity.

Another option is to query entities with MergeOption.NoTracking option.

http://msdn.microsoft.com/en-us/library/system.data.objects.mergeoption.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top