Entity Framework Core 1.0.0 Disable Eager/Lazy Loading




Can't seem to find any mention of this for EF Core. I've found examples to disable lazy loading in prior EF versions. I have an asp.net core, MVC6, Web Api, and AngularJS site I'm working on. 


In the app, I have a table Members and a table MemberStateActions which has a foreign key reference to the Members table. I'm selecting the data using the query below, and then returning the data via Web Api call as Json return type.
The resulting MemberStateActions object returned via Web Api has the MemberStateAction.Member object populated. I did not eager load the Member data using .include. I did not lazy load the Member object by calling the property. I don't understand why the Member data is automatically populated. I've read that json serialization maybe be calling the member property causing the lazy loading of the member data before being sent in the Web Api response. Not sure if this is the cause. 


Bottom line, I'm looking on some direction as to how to prevent this automatic loading of the member object. Possibly by disabling lazy loading? 



```
        var q = (from x in _context.MemberStateAction
                 where x.MemberId == memberID
                 select x);

        return q;

```
Entity Framework Core does not have lazy loading implemented at this time (RTM Build).


It is recommended that you do eager loading by using an .Include extension method. It is also a good idea to use a repository to do the eager loading for you.


Reference: <https://github.com/aspnet/EntityFramework/issues/3797>
The documentation for [`ConfigurationManager.RefreshSection`](https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.refreshsection?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev15.query%3FappId%3DDev15IDEF1%26l%3DEN-US%26k%3Dk(System.Configuration.ConfigurationManager.RefreshSection);k(TargetFrameworkMoniker-.NETFramework,Version%3Dv4.6.2);k(DevLang-csharp)%26rd%3Dtrue&view=netframework-4.7.2) method does say (emphasis is mine):



> 
> Refreshes the named section **so the next time that it is retrieved** it will be re-read from disk.
> 
> 
> 


The problem is that EF6 caches the [`ConfigurationManager.ConnectionStrings`](https://docs.microsoft.com/en-us/dotnet/api/system.configuration.configurationmanager.connectionstrings?view=netframework-4.7.2) in an internal class static property, so it never gets refreshed.


Unfortunately there is no "official" way to refresh it. Following is a brute force hack using reflection, so use it on your own risk:



```
static readonly Type EF6AppConfigType = typeof(DbContext).Assembly.GetType("System.Data.Entity.Internal.AppConfig");

static readonly PropertyInfo EF6DefaultAppConfig = EF6AppConfigType.GetProperty("DefaultInstance", BindingFlags.Public | BindingFlags.Static);

static readonly FieldInfo EF6ConnectionStrings = EF6AppConfigType.GetField("_connectionStrings", BindingFlags.NonPublic | BindingFlags.Instance);

static void RefreshEF6ConnectionStrings()
{
    EF6ConnectionStrings.SetValue(
        EF6DefaultAppConfig.GetValue(null),
        ConfigurationManager.ConnectionStrings
    );
}

```

Just call it after saving the changes:



```
config.Save();
RefreshEF6ConnectionStrings();

``` I suppose you could try overriding the encoding in the `HtmlWeb` object.


Try this:



```
var web = new HtmlWeb
{
    AutoDetectEncoding = false,
    OverrideEncoding = myEncoding,
};
var doc = web.Load(myUrl);

```

Note: It appears that the `OverrideEncoding` property was added to HTML agility pack in revision 76610 so it is not available in the current release v1.4 (66017). The next best thing to do would be to read the page manually with the encodings overridden. Dapper just wraps raw ADO.NET; raw ADO.NET doesn't offer a facility for this, therefore dapper does not. What you want is `SqlBulkCopy`. You could *also* use a table-valued-parameter, but this really feels like a `SqlBulkCopy` job.


In a pinch, you can *use* dapper here - `Execute` will unroll an `IEnumerable<T>` into a series of commands about `T` - but it will be lots of commands; and unless you explicitly enable async-pipelining, it will suffer from latency per-command (the pipelined mode avoids this, but it will still be n commands). But `SqlBulkCopy` will be *much* more efficient.


If the input data is an `IEnumerable<T>`, you might want to use `ObjectReader` from FastMember; for example:



```
IEnumerable<SomeType> data = ...
using(var bcp = new SqlBulkCopy(connection))
using(var reader = ObjectReader.Create(data, "Id", "Name", "Description"))
{
    bcp.DestinationTableName = "SomeTable";
    bcp.WriteToServer(reader);
}

``` hi, 
  
we did try following: 
  
1. update java to the latest version 
this didn't affect the cpu or ram consumption. 
  
2. assign more ram for java, we found on other forums that high pcu consumption was caused by lack of memory. 
this didn't affect the cpu consumption neither 
  
3. change the port for connector from 8443 to to save resources for port redirection. 
the cpu consumption for the redirection is so low that it didn't change either 
  
4. try to disable autodeploy and do it manually 
we couldn't do this as the concerned era is allready in production 
  
5. do you have issues with http traffic as well or just with https? 
as we are working on security, there is just no http at all ! (disabled in tomcat) 
  
  
but we found out that regarding the place from which we did connect (and the available bandwith) it did impact the behavior. 
whith a good bandwith: the page loads in something as 10 to 15 seconds and cpu load doesn't go at 100% or just for the few last seconds 
whith a bad bandwith: the page takes 1 to 3 minutes to load and cpu consumption goes to 100% (over several cores) after the 10 first seconds (just like a memory leak but with cpu). 
  
we don't get why but the longer it takes for the client's side (browser) to load the app, how more cpu is consumes on server... so got the solution from support:

1) ecli task.list include\_completed=false
2) ~/bin/ergon\_update\_task --task\_uuid=9 --task\_status=aborted Using [reflection](/questions/tagged/reflection "show questions tagged 'reflection'") and [expression-trees](/questions/tagged/expression-trees "show questions tagged 'expression-trees'") you can provide the parameters and then call `OrderBy` function, Instead of returning `Expression<Func<Task, T>>` and then calling `OrderBy`.


Note that `OrderBy` is an extension method and has implemented in both `System.Linq.Enumarable` and `System.Linq.Queryable` classes. The first one is for [linq-to-objects](/questions/tagged/linq-to-objects "show questions tagged 'linq-to-objects'") and the latter is for [linq-to-entities](/questions/tagged/linq-to-entities "show questions tagged 'linq-to-entities'"). [entity-framework](/questions/tagged/entity-framework "show questions tagged 'entity-framework'") needs the expression tree of the query in order to translate it to SQL commands. So we use the `Queryable` implementation.


It can be done by an extension method(explanations added as comments):



```
public static IOrderedQueryable<TSource> OrderBy<TSource>(
       this IQueryable<TSource> query, string propertyName)
{
    var entityType = typeof(TSource);

    //Create x=>x.PropName
    var propertyInfo = entityType.GetProperty(propertyName);
    ParameterExpression arg = Expression.Parameter(entityType, "x");
    MemberExpression property = Expression.Property(arg, propertyName);
    var selector = Expression.Lambda(property, new ParameterExpression[] { arg });

    //Get System.Linq.Queryable.OrderBy() method.
    var enumarableType = typeof(System.Linq.Queryable);
    var method = enumarableType.GetMethods()
         .Where(m => m.Name == "OrderBy" && m.IsGenericMethodDefinition)
         .Where(m =>
         {
            var parameters = m.GetParameters().ToList();
            //Put more restriction here to ensure selecting the right overload                
            return parameters.Count == 2;//overload that has 2 parameters
         }).Single();
    //The linq's OrderBy<TSource, TKey> has two generic types, which provided here
    MethodInfo genericMethod = method
         .MakeGenericMethod(entityType, propertyInfo.PropertyType);

    /*Call query.OrderBy(selector), with query and selector: x=> x.PropName
      Note that we pass the selector as Expression to the method and we don't compile it.
      By doing so EF can extract "order by" columns and generate SQL for it.*/
    var newQuery = (IOrderedQueryable<TSource>)genericMethod
         .Invoke(genericMethod, new object[] { query, selector });
    return newQuery;
}

```

Now you can call this overload of `OrderBy` like any other overload of it.  

For example:



```
var cheapestItems = _context.Items.OrderBy("Money").Take(10).ToList();

```

Which translates to:



```
SELECT TOP (10)  {coulmn names} FROM  [dbo].[Items] AS [Extent1] 
       ORDER BY [Extent1].[Money] ASC

```

This approach can be used to define all overloads of `OrderBy` and `OrderByDescending` methods to have `string` property selector. you should be able to set the element to not be visible on page load, and then on the conditional tab of the element, you should be able to construct a condition where parent group’s thing’s creation date < parent group’s thing’s modified date, this element is visible. and when i say “should be able… i suspect that the resource\_exhausted message may have originated from a back-pressuring committer node ([code](https://github.com/digital-asset/daml/blob/926fb5997a795e7f80443a9a3ba7898b1568d158/ledger/participant-integration-api/src/main/scala/platform/apiserver/services/apisubmissionservice.scala#l155-l157)). if that’s the case, i believe the approach should be the same: change the configuration if you need and make sure to handle those errors with the appropriate retry strategy. A few things to try.


1. Use [Variable Tables](http://odetocode.com/Articles/365.aspx) instead -> maybe the import wizard prefers that?
2. Name your return fields.


Try using the following stored proc (untested .. just thinking out loud...)



```
CREATE PROCEDURE dbo.Foo
AS

    SET NOCOUNT ON

    DECLARE @ResultTable TABLE (SomeId INTEGER)

    INSERT INTO @ResultTable
    SELECT DISTINCT Id AS Identity -- Or u can rename this field to anything...
    FROM SomeExistingTableWhichHasAnIdentityField

GO

```

Try that and see if the wizard refreshes, now.


-- 


 Attempt #2 :)


Ok .. when the EF designer/wizard/whatever fails to figure out EXACTLY what my stored proc is suppose to be returning, I usually do the following :-


1. Make sure the stored procedure doesn't exist at all in the EF designer/context, etc. (You have a clean starting point)
2. Open up your stored procedure and `/* /*` comment out *EVERYTHING* after the procedure definition.


eg..



```
ALTER PROCEDURE dbo.Foo
(
    Bar1 INT,
    Bar2 TINYINT,
    ... // whatever u have as your optional input arguments //
)
AS
    SET NOCOUNT ON

    /* 
    .... every thing in here is commented out 
    */
GO

```

Now ...
 3. Add a forced fake return in the stored proc, which (more or less) just *defines* the output structure/fields.


eg..



```
ALTER PROCEDURE dbo.Foo
(
    Bar1 INT,
    Bar2 TINYINT,
    ... // whatever u have as your optional input arguments //
)
AS
    SET NOCOUNT ON

    SELECT 1 AS Id, 1 AS UserId, 1 AS SomeOtherId, 
        CAST('AAA' AS NVARCHAR(350)) AS Name,
        -- etc etc etc..
    /* 
    .... every thing in here is commented out 
    */
GO

```

[and then](http://www.youtube.com/watch?v=K7luMp6lb9M) ...


4. Add this stored proc to your EF designer/wizard/etc... Now the correct fields should be 'determined' by the designer. AWESOME. Yes .. the values are all hardcoded .. but that's ok (so far).
5. Once your happy that EF is now updated right, go back to your stored proc, and remove all hardcoded SELECT (which we did in the above step). Now we remove the comments which we commented out the entire real code. So you should have your original stored proc, back.


... and now EF is updated and doesn't know we've changed the plumbing of your stored proc.


win :)


does this work for ya? hi larry, - - thank you for writing. - - to disable the arrow keys you need to override the onkeydown method:  - - class mypageview : radpageview - { -     protected override void onkeydown(keyeventargs e) -     { -         if (e.keycode == keys.left || e.keycode == keys.right) -         { -             return; -         } -         base.onkeydown(e); -     } - } - - - i hope this information is useful. let me know if you need further assistance. - - regards, - dimitar - telerik by progress - - try our brand new, jquery-free angular 2 components built from ground-up which - deliver the business app essential building blocks - a grid component, - data visualization (charts) and form elements. -