Do not delete property after expression using

I have a small question on entity infrastructure 4.1.

There is a DTO image interface:

public interface IImage : IDtoBase { string FullFilePath { get; set; } int Width { get; set; } int Heigth { get; set; } long ImageTypeId { get; set; } IImageType Type { get; set; } } 

There is a code for setting the context:

 // where TContext : DbContext, new() private TInterface Invoke(Func<TContext, TInterface> callback) { using (var context = new TContext()) { context.Configuration.AutoDetectChangesEnabled = true; context.Configuration.LazyLoadingEnabled = true; context.Configuration.ProxyCreationEnabled = true; context.Configuration.ValidateOnSaveEnabled = true; context.Database.Connection.Open(); return callback.Invoke(context); } } 

To get the required DTO element, there is a code:

 public TInterface Get(long id) { return Invoke( context => { TDto dto = context.Set<TDto>().FirstOrDefault(x => (x.Id == id)); return dto.Convert<TDto, TInterface>(); } ); } 

If I set context.Configuration.LazyLoadingEnabled = false , then the "Type" property of the DTO image is null (I think this is normal).

If context.Configuration.LazyLoadingEnabled has a "true" value, then the "Type" property of the DTO image has the correct value inside the "using" statement, but this property is deleted after the context is deleted - "the ObjectContext instance has been deleted and may no longer be used for operations requiring connect. "

those. the DTO image exists / is not located, but its Type property is already located.

Can someone provide any solution - do not remove the “Type” property (I would like to use the “using” expression instead of the “Dispose” template)?

+4
source share
1 answer

First of all, you need to understand how lazy loading works. EF does this by creating a proxy server that inherits from your entity class and overrides the navigation property access behavior. At the first access to the navigation property, if it was not loaded before the proxy class will load it through the context . Consequently, proxy instances contain a reference to the context.

When execution leaves your Invoke method, the context will be deleted. Therefore, the proxy cannot be lazy to load navigation properties. There are several things you can do to solve this problem.

  • Retaining Navigation Properties

use the include method to load the load

 public TInterface Get(long id) { return Invoke( context => { TDto dto = context.Set<TDto>().Include(t => t.Type) .FirstOrDefault(x => (x.Id == id)); return dto.Convert<TDto, TInterface>(); } ); } 
  • Controlling the lifetime of the context Without deleting the context directly inside the Invoke method, you can use an existing instance of the context that will be deleted after you finish accessing the data. This can be done with the IoC / DI framework. For web projects, the lifetime is usually limited to a single request.
+4
source

All Articles