Showing posts with label Entity Framework. Show all posts
Showing posts with label Entity Framework. Show all posts

Monday, November 16, 2015

How to use stored procedure with Entity Framework Code First

To learn about how we can use stored procedure with Entity framework code first, jalpesh vadgama has written a very good blog post here.

Thanks jalpesh vadgama.

Monday, October 5, 2015

EntityFramework Performance and AutoDetectChanges

What is Auto Detect Changes?

Entity framework has two methods of change detection built into the framework, Instant Notification and Snapshot. Most people seem to use the Snapshot mechanism as it is the easiest to configure and most well known. I will cover the Instant Notification (Proxy Entities) Mechanism in a later post.

Wednesday, June 5, 2013

Difference Between Entity SQL and Transact-SQL

Entity SQL is a SQL-like language that enables you to query conceptual models in the Entity Framework. Conceptual models represent data as entities and relationships, and Entity SQL allows you to query those entities and relationships in a format that is familiar to those who have used SQL. Transact-SQL is extension to SQL created for communicating with SQL Server. All applications that communicate with an instance of SQL Server do so by sending Transact-SQL statements to the server, regardless of the user interface of the application.
Both sounds similar but there are many differences between these two. Following table represents those differences.
Entity SQLTransact-SQL
Is a language similar to SQL used to work with an Entity Data Model (EDM).Is an ANSI SQL language used for stored procedures and functions.
Is used to work with conceptual entities by supporting features like inheritance and relationships.Is used to write stored procedures in relational databases.
Supports collections and considers them as first class entities.Does not support collections but does support subqueries and expressions.
Interprets all subqueries to be multiset subqueries, irrespective of the context in which they are used.Interprets subqueries as per the context in which they are used.
Allows expressions defined in a from clause to reference earlier expressions defined to the left in the same clause.Does not allow expressions to reference earlier expressions defined in the same scope, such as in a select clause.
Table columns can only be referenced by qualifying them with a table alias, except in from clauses where table aliases are optional.Table columns are referenced directly.
Uses the “.” notation to navigate through the properties of an object.Uses the “.” notation to reference columns.
Does not support the * construct.Supports the * construct.
Supports SQL-style aggregates and collection-based aggregates.Supports only SQL-based aggregates.
Allows nested ORDER By expressions anywhere in the queries.Allows ORDER By clauses only in the top most SELCT, FROM, and WHERE clauses of the queries.
Identifiers are compared according to the case and accent.Identifiers are compared according to the current database collation.
Supports a subset of Transact-SQL’s built in functions and operators.Supports additional functionalities that are not supported in Entity SQL including:
Analytic Functions
Builtin Functions, Operators
DDL
DML -insert, update, delete.

Saturday, December 15, 2012

Entity Framework 6: Alpha2 Now Available

Entity Framework 6: Alpha2 Now Available:
The Entity Framework team recently announced the 2nd alpha release of EF6.   The alpha 2 package is available for download from NuGet. Since this is a pre-release package make sure to select “Include Prereleases” in the NuGet package manager, or execute the following from the package manager console to install it:
PM> Install-Package EntityFramework -Pre
This week’s alpha release includes a bunch of great improvements in the following areas:
  • Async language support is now available for queries and updates when running on .NET 4.5.
  • Custom conventions now provide the ability to override the default conventions that Code First uses for mapping types, properties, etc. to your database.
  • Multi-tenant migrations allow the same database to be used by multiple contexts with full Code First Migrations support for independently evolving the model backing each context.
  • Using Enumerable.Contains in a LINQ query is now handled much more efficiently by EF and the SQL Server provider resulting greatly improved performance.
  • All features of EF6 (except async) are available on both .NET 4 and .NET 4.5. This includes support for enums and spatial types and the performance improvements that were previously only available when using .NET 4.5.
  • Start-up time for many large models has been dramatically improved thanks to improved view generation performance.
Below are some additional details about a few of the improvements above:

Async Support

.NET 4.5 introduced the Task-Based Asynchronous Pattern that uses the async and await keywords to help make writing asynchronous code easier. EF 6 now supports this pattern. This is great for ASP.NET applications as database calls made through EF can now be processed asynchronously – avoiding any blocking of worker threads. This can increase scalability on the server by allowing more requests to be processed while waiting for the database to respond.
The following code shows an MVC controller that is querying a database for a list of location entities:
    public class HomeController : Controller
    {
        LocationContext db = new LocationContext();

        public async Task<ActionResult> Index()
        {
            var locations = await db.Locations.ToListAsync();

            return View(locations);
        }
    }
Notice above the call to the new ToListAsync method with the await keyword. When the web server reaches this code it initiates the database request, but rather than blocking while waiting for the results to come back, the thread that is processing the request returns to the thread pool, allowing ASP.NET to process another incoming request with the same thread. In other words, a thread is only consumed when there is actual processing work to do, allowing the web server to handle more concurrent requests with the same resources.
A more detailed walkthrough covering async in EF is available with additional information and examples. Also a walkthrough is available showing how to use async in an ASP.NET MVC application.

Custom Conventions

When working with EF Code First, the default behavior is to map .NET classes to tables using a set of conventions baked into EF. For example, Code First will detect properties that end with “ID” and configure them automatically as primary keys.
However, sometimes you cannot or do not want to follow those conventions and would rather provide your own. For example, maybe your primary key properties all end in “Key” instead of “Id”. Custom conventions allow the default conventions to be overridden or new conventions to be added so that Code First can map by convention using whatever rules make sense for your project.
The following code demonstrates using custom conventions to set the precision of all decimals to 5. As with other Code First configuration, this code is placed in the OnModelCreating method which is overridden on your derived DbContext class:
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Properties<decimal>()
                .Configure(x => x.HasPrecision(5));

        }
But what if there are a couple of places where a decimal property should have a different precision? Just as with all the existing Code First conventions, this new convention can be overridden for a particular property simply by explicitly configuring that property using either the fluent API or a data annotation.
A more detailed description of custom code first conventions is available here.

Community Involvement

I blogged a while ago about EF being released under an open source license.  Since then a number of community members have made contributions and these are included in EF6 alpha 2.
Two examples of community contributions are:
  • AlirezaHaghshenas contributed a change that increases the startup performance of EF for larger models by improving the performance of view generation. The change means that it is less often necessary to use of pre-generated views.
  • UnaiZorrilla contributed the first community feature to EF: the ability to load all Code First configuration classes in an assembly with a single method call like the following:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
       modelBuilder.Configurations
           .AddFromAssembly(
typeof(LocationContext).Assembly);

}
This code will find and load all the classes that inherit from EntityTypeConfiguration<T> or ComplexTypeConfiguration<T> in the assembly where LocationContext is defined. This reduces the amount of coupling between the context and Code First configuration classes, and is also a very convenient shortcut for large models.

Other upcoming features coming in EF 6

Lots of information about the development of EF6 can be found on the EF CodePlex site, including a roadmap showing the other features that are planned for EF6.
One of of the nice upcoming features is connection resiliency, which will automate the process of retying database operations on transient failures common in cloud environments and with databases such as the Windows Azure SQL Database.
Another often requested feature that will be included in EF6 is the ability to map stored procedures to query and update operations on entities when using Code First.

Summary

EF6 is the first open source release of Entity Framework being developed in CodePlex. The alpha 2 preview release of EF6 is now available on NuGet, and contains some really great features for you to try.
The EF team are always looking for feedback from developers - especially on the new features such as custom Code First conventions and async support. To provide feedback you can post a comment on the EF6 alpha 2 announcement post, start a discussion or file a bug on the CodePlex site.
Hope this helps,
Vihang

Sunday, December 9, 2012

Conventions for Code First


The latest preview of Code First allows you to describe a model using C# or VB.Net classes. The basic shape of the model is detected by convention and then a fluent API can be used to further refine your model.
We recently posted about our plans to support Data Annotations as another way to further describe your model. We are now looking at extending and improving the conventions that initially infer the shape of the model. This post describes the conventions we are planning to include.
Conventions are designed to provide a starting point for a model. Data Annotations or the fluent API can then be used to further describe the model or change what was detected by convention. Precedence is given to configuration via the fluent API followed by Data Annotations then convention.

For more read here.

The Repository Pattern with EF Code First & Dependency Injection in ASP.NET MVC3


Introduction

These days, I started using EF code first and thought about how could I take advantage from it for my recent project. My project is based on MVC3 and there are some challenges to continue updating this project. At that time, I must finish my job in a very short deadline so fast so good I just define some data access interfaces and implemented them with EF4.
There are some things in my project troubling me:
  • I have used the EF entities in my controllers anywhere that there is a connection translation error throwing infrequently.
  • Modules coupling degree becoming closed.
  • Manage services and contexts life cycle are difficult.
Obviously, it needs to refactor my project with a new architecture designing.

More to read here.

Code First with Entity Framework 5 using MVC4 and MVC Scaffold


Introduction

In this article, I will walk you through a simple application using MVC4 and Entity Framework 5 and will demonstrate how one can make use of code first technology. I will be using MvsScaffold for quick creation of controllers and views. We will be creating a TODO application.

More to read here.

Finally! Entity Framework working in fully disconnected N-tier web app


Introduction 

Entity Framework was supposed to solve the problem of Linq to SQL, which requires endless hacks to make it work in n-tier world. Not only did Entity Framework solve none of the L2S problems, but also it made it even more difficult to use and hack it for n-tier scenarios. It’s somehow half way between a fully disconnected ORM and a fully connected ORM like Linq to SQL. Some useful features of Linq to SQL are gone – like automatic deferred loading. If you try to do simple select with join, insert, update, delete in a disconnected architecture, you will realize not only you need to make fundamental changes from the top layer to the very bottom layer, but also endless hacks in basic CRUD operations. I will show you in this article how I have  added custom CRUD functions on top of EF’s ObjectContext to make it finally work well in a fully disconnected N-tier web application (my open source Web 2.0 AJAX portal – Dropthings) and how I have produced a 100% unit testable fully n-tier compliant data access layer following the repository pattern.
In .NET 4.0, most of the problems are solved, but not all. So, you should read this article even if you are coding in .NET 4.0. Moreover, there’s enough insight here to help you troubleshoot EF related problems.
You might think “Why bother using EF when Linq to SQL is doing good enough for me.” Linq to SQL is not going to get any innovation from Microsoft anymore. Entity Framework is the future of persistence layer in .NET framework. All the innovations are happening in EF world only, which is frustrating. There’s a big jump on EF 4.0. So, you should plan to migrate your L2S projects to EF soon.

For More read here.

Hope you like this article friendz... :)

Find a cool free stuff everyday

Giveaway of the Day

Hiren Bharadwa's Posts

DotNetJalps