Tuesday, December 24, 2013

Loading Entities in Entity Framework

In Entity Framework you can load data in few different ways,
  • Eager loading
  • Lazy loading
  • Explicit loading

Eager Loading

Here query for a one type of entity also loads other related entities as a part of the query. You can load related entities by using Include method. Include is an extension method.

        List<Employee> employees = context.Employees
            .Include(e => e.Courses)
            .ToList();


        List<Employee> employees2 = context.Employees
            .Include("Courses")
            .ToList();

This will generate a left outer join (See diagram for types of joins) thereby, if no record found it will return null for them.



You can also load multiple levels of related entities. In eager loading, there won't be multiple database calls.  It retrieves all data at once. The downside is, it creates large nested queries which has a performance impact. Therefore avoid using multiple Include statements in a single LINQ query. See Performance considerations. See SO Questions.

Lazy Loading

Loads related entities automatically the first time the property referring the entity is accessed.

Lazy loading and serialization doesn't get together well. Most serializers work by accessing each property of an instance of a type. This property access triggers lazy loading. Therefore it is recommended to turn off lazy loading before serializing an entity. 


Explicit loading

Even with lazy loading off, you can load related entities lazily. By explicitly calling Load method.

References

Saturday, December 21, 2013

DbContext in Entity Framework

Entity Framework, commonly known as EF (latest being EF Core) is a ORM tool which is introduced and maintained by Microsoft.

In EF, DbContext Is the primary class which is used to interact with data as objects. DbContext is often referred to as context. The context class manages entity objects during run time, which includes populating data from database, change tracking and persisting data back to database.  

What exactly is DbContext class?

DbContext is actually a simplified alternative to ObjectContext. Its like a wrapper over ObjectContext. DbContext is the preferred way to interact with Entity Framework. (Is DbContext same as DataContext?). You can get ObjectContext from DbContext using the following code.


DbContext is most commonly used with derived type that contains DbSet<Entity> properties for the root entities of the model. These sets are automatically initialized when a derived type of DbContext is created. You can override protected method OnModelCreating to modify these models. (See Code First Building Blocks).

What is DbSet?

DbSet represents a table or a view in the database. DbSet(TEntity) cannot be constructed publicly. It can be instantiated only through DbContext instance. See DbSet and DbContext. You will be using DbSet to access, insert, update or delete your table data.

Lifetime of DbContext starts when object is created and ends when the object is disposed or garbage collected. By default context manages connections to the database. The context opens and closes connections as necessary. 

DbContext is not thread safe.You can still create multi-threaded applications as long as instance of same DbContext class is not tracked by multiple contexts at the same time. 

Here's some insight of DbContext class. You can find the source code in codeplex.

DbModelBuilder
Used to map CLR classes to database schema. This is mainly used in Code First approach. MSDN


Timeout in Entity Framework
Entity Framework operations have timeouts. The timeout duration is defined by underlying connection providers. You can set the connection timeout in Entity Framework connection string but there is a known bug in MySQL. Therefore you can set timeout in data context.

this.context.Database.CommandTimeout = 180; 


Overridable members in DbContext

Dispose : Usually you don't need to do this. see this article
SaveChanges and SaveChangesAsync : EF6 onwards 
ValidateEntity and ShouldValidateEntity : see this 


Change Tracking POCO entities

In EF, you can track POCO entity changes through change-tracking proxy object or through a snapshot.

When change tracking with proxies, tracking changes in object graph is automatically done by EF. You can disable proxy creation this using below command. Beware that even if proxy creation is enabled, EF will create proxy classes only if the requirements for proxy creation is satisfied.

entities.Configuration.ProxyCreationEnabled = false;

Proxies are created for lazy loading as well. Not only for change tracking

http://stackoverflow.com/questions/7111109/should-i-enable-or-disable-dynamic-proxies-with-entity-framework-4-1-and-mvc3
https://msdn.microsoft.com/en-us/library/vstudio/dd456848(v=vs.100).aspx
https://msdn.microsoft.com/en-us/library/vstudio/dd456848(v=vs.100).aspx
http://stackoverflow.com/questions/26355486/entity-framework-6-audit-track-changes
http://www.entityframeworktutorial.net/change-tracking-in-entity-framework.aspx
http://www.c-sharpcorner.com/UploadFile/ff2f08/working-with-change-tracking-proxy-in-entity-framework-6-0/

Attaching and Detaching Entities

Objects that are attached to ObjectContext can be tracked and managed by ObjectContext. When your object is detached, it won't be tracked by the object context. By default if you execute a query inside a ObjectContext, entities are attached to object context. 

You can detach entities by one of the options below,

Using MergeOption.NoTracking enumeration or AsNoTracking
See examples here, here and here. Also beware about possible performance issues as mentioned here and here. See advantages of using AsNoTracking here and here.

ObjectContext.Detach method
This method removes the object from ObjectStateManager. Disables change tracking and identity resolution. See the example below,

https://msdn.microsoft.com/en-us/library/vstudio/bb896271(v=vs.100).aspx
http://stackoverflow.com/questions/4168073/entity-framework-code-first-no-detach-method-on-dbcontext

See Working with DbContext (MSDN)
See example files used in this article in this gist

Saturday, December 7, 2013

Performance considerations in KnockoutJS

For web applications performance is an important factor to consider. In KnockoutJS when you do things in the wrong way this matters. We'll see some key areas you need to consider about performance in KnockoutJS. 

First lets look at fundemental building blocks of KnockoutJS application

observables
most basic fundamental building block. You need to have these

observableArrays

subscribers
get notifications when observable gets changed. You can dispose these. Also you delay them in case of expensive updates.

computed observables
Observables which depends on other observables


Bindings in KnockoutJS



visible binding
set display none based on the value. So shouldn't cost much.

for 10,000 elements inside a foreach, ko if takes around 10 seconds while visible binding only takes 1 second.

foreach
duplicates section of a markup for each array entry. Could be a normal array . 

if
bit expensive because, not like visible binding, if will hide the content which is inside the tag

    <div data-bind="if: check">
        <h1>Inject this to DOM if check is true</h1>
        <h2>Otherwise this won't exist in the DOM</h2>
    </div>

the visible binding just uses CSS to toggle the container element’s visiblity. The if binding, however, physically adds or removes the contained markup in your DOM, and only applies bindings to descendants if the expression is true.

with
creates a new binding context. it'll add descendent elements dynamically.

If the expression you supply involves any observable values, the expression will be re-evaluated whenever any of those observables change. Then, descendant elements will be cleared out, and a new copy of the markup will be added to your document and bound in the context of the new evaluation result.


click


value


checked


template


custom bindings


Monday, December 2, 2013

Powered by Blogger.


Software Architect at Surge Global/ Certified Scrum Master

Experienced in Product Design, Software Engineering, Team management and Practicing Agile methodologies.

Search This Blog

Facebook