[.net] Entity Framework vs LINQ to SQL

Now that .NET v3.5 SP1 has been released (along with VS2008 SP1), we now have access to the .NET entity framework.

My question is this. When trying to decide between using the Entity Framework and LINQ to SQL as an ORM, what's the difference?

The way I understand it, the Entity Framework (when used with LINQ to Entities) is a 'big brother' to LINQ to SQL? If this is the case - what advantages does it have? What can it do that LINQ to SQL can't do on its own?

This question is related to .net entity-framework linq-to-sql

The answer is


Is LINQ to SQL Truly Dead? by Jonathan Allen for InfoQ.com

Matt Warren describes [LINQ to SQL] as something that "was never even supposed to exist." Essentially, it was just supposed to be stand-in to help them develop LINQ until the real ORM was ready.

...

The scale of Entity Framework caused it to miss the .NET 3.5/Visual Studio 2008 deadline. It was completed in time for the unfortunately named ".NET 3.5 Service Pack 1", which was more like a major release than a service pack.

...

Developers do not like [ADO.NET Entity Framework] because of the complexity.

...

as of .NET 4.0, LINQ to Entities will be the recommended data access solution for LINQ to relational scenarios.



I think if you need to develop something quick with no Strange things in the middle, and you need the facility to have entities representing your tables:

Linq2Sql can be a good allied, using it with LinQ unleashes a great developing timing.


Linq-to-SQL

It is provider it supports SQL Server only. It's a mapping technology to map SQL Server database tables to .NET objects. Is Microsoft's first attempt at an ORM - Object-Relational Mapper.

Linq-to-Entities

Is the same idea, but using Entity Framework in the background, as the ORM - again from Microsoft, It supporting multiple database main advantage of entity framework is developer can work on any database no need to learn syntax to perform any operation on different different databases

According to my personal experience Ef is better (if you have no idea about SQL) performance in LINQ is little bit faster as compare to EF reason LINQ language written in lambda.


I found a very good answer here which explains when to use what in simple words:

The basic rule of thumb for which framework to use is how to plan on editing your data in your presentation layer.

  • Linq-To-Sql - use this framework if you plan on editing a one-to-one relationship of your data in your presentation layer. Meaning you don't plan on combining data from more than one table in any one view or page.

  • Entity Framework - use this framework if you plan on combining data from more than one table in your view or page. To make this clearer, the above terms are specific to data that will be manipulated in your view or page, not just displayed. This is important to understand.

With the Entity Framework you are able to "merge" tabled data together to present to the presentation layer in an editable form, and then when that form is submitted, EF will know how to update ALL the data from the various tables.

There are probably more accurate reasons to choose EF over L2S, but this would probably be the easiest one to understand. L2S does not have the capability to merge data for view presentation.


My experience with Entity Framework has been less than stellar. First, you have to inherit from the EF base classes, so say good bye to POCOs. Your design will have to be around the EF. With LinqtoSQL I could use my existing business objects. Additionally, there is no lazy loading, you have to implement that yourself. There are some work arounds out there to use POCOs and lazy loading, but they exist IMHO because EF isn't ready yet. I plan to come back to it after 4.0


If your database is straightforward and simple, LINQ to SQL will do. If you need logical/abstracted entities on top of your tables, then go for Entity Framework.


I think the quick and dirty answer is that

  • LINQ to SQL is the quick-and-easy way to do it. This means you will get going quicker, and deliver quicker if you are working on something smaller.
  • Entity Framework is the all-out, no-holds-barred way to do it. This means you will take more time up-front, develop slower, and have more flexibility if you are working on something larger.

I am working for customer that has a big project that is using Linq-to-SQL. When the project started it was the obvious choice, because Entity Framework was lacking some major features at that time and performance of Linq-to-SQL was much better.

Now EF has evolved and Linq-to-SQL is lacking async support, which is great for highly scalable services. We have 100+ requests per second sometimes and despite we have optimized our databases, most queries still take several milliseconds to complete. Because of the synchronous database calls, the thread is blocked and not available for other requests.

We are thinking to switch to Entity Framework, solely for this feature. It's a shame that Microsoft didn't implement async support into Linq-to-SQL (or open-sourced it, so the community could do it).

Addendum December 2018: Microsoft is moving towards .NET Core and Linq-2-SQL isn't support on .NET Core, so you need to move to EF to make sure you can migrate to EF.Core in the future.

There are also some other options to consider, such as LLBLGen. It's a mature ORM solution that exists already a long time and has been proven more future-proof then the MS data solutions (ODBC, ADO, ADO.NET, Linq-2-SQL, EF, EF.core).


LINQ to SQL

  1. Homogeneous datasource: SQL Server
  2. Recommended for small projects only where data structure is well designed
  3. Mapping can be changed without recompilling with SqlMetal.exe
  4. .dbml (Database Markup Language)
  5. One-to-one mapping between tables and classes
  6. Supports TPH inheritance
  7. Doesn't support complex types
  8. Storage-first approach
  9. Database-centric view of a database
  10. Created by C# team
  11. Supported but not further improvements intended

Entity Framework

  1. Heterogeneus datasource: Support many data providers
  2. Recommended for all new projects except:
    • small ones (LINQ to SQL)
    • when data source is a flat file (ADO.NET)
  3. Mapping can be changed without recompilling when setting model and mapping files Metadata Artifact Process to Copy To Output Directory
  4. .edmx (Entity Data Model) which contains:
    • SSDL (Storage Schema Definition Language)
    • CSDL (Conceptual Schema Definition Language)
    • MSL (Mapping Specification Language)
  5. One-to-one, one-to-many, many-to-one mappings between tables and classes
  6. Supports inheritence:
    • TPH (Table Per Hierarchy)
    • TPT (Table Per Type)
    • TPC (Table Per Concrete Class)
  7. Supports complex types
  8. Code-first, Model-first, Storage-first approaches
  9. Application-centric view of a database
  10. Created by SQL Server team
  11. Future of Microsoft Data APIs

See also:


Neither yet supports the unique SQL 2008 datatypes. The difference from my perspective is that Entity still has a chance to construct a model around my geographic datatype in some future release, and Linq to SQL, being abandoned, never will.

Wonder what's up with nHibernate, or OpenAccess...


My impression is that your database is pretty enourmous or very badly designed if Linq2Sql does not fit your needs. I have around 10 websites both larger and smaller all using Linq2Sql. I have looked and Entity framework many times but I cannot find a good reason for using it over Linq2Sql. That said I try to use my databases as model so I already have a 1 to 1 mapping between model and database.

At my current job we have a database with 200+ tables. An old database with lots of bad solutions so there I could see the benefit of Entity Framework over Linq2Sql but still I would prefer to redesign the database since the database is the engine of the application and if the database is badly designed and slow then my application will also be slow. Using Entity framework on such a database seems like a quickfix to disguise the bad model but it could never disguise the bad performance you get from such a database.


Here's some metrics guys... (QUANTIFYING THINGS!!!!)

I took this query where I was using Entity Framework

var result = (from metattachType in _dbContext.METATTACH_TYPE
                join lineItemMetattachType in _dbContext.LINE_ITEM_METATTACH_TYPE on metattachType.ID equals lineItemMetattachType.METATTACH_TYPE_ID
                where (lineItemMetattachType.LINE_ITEM_ID == lineItemId && lineItemMetattachType.IS_DELETED == false
                && metattachType.IS_DELETED == false)
                select new MetattachTypeDto()
                {
                    Id = metattachType.ID,
                    Name = metattachType.NAME
                }).ToList();

and changed it into this where I'm using the repository pattern Linq

            return await _attachmentTypeRepository.GetAll().Where(x => !x.IsDeleted)
                .Join(_lineItemAttachmentTypeRepository.GetAll().Where(x => x.LineItemId == lineItemId && !x.IsDeleted),
                attachmentType => attachmentType.Id,
                lineItemAttachmentType => lineItemAttachmentType.MetattachTypeId,
                (attachmentType, lineItemAttachmentType) => new AttachmentTypeDto
                {
                    Id = attachmentType.Id,
                    Name = attachmentType.Name
                }).ToListAsync().ConfigureAwait(false);

Linq-to-sql

            return (from attachmentType in _attachmentTypeRepository.GetAll()
                    join lineItemAttachmentType in _lineItemAttachmentTypeRepository.GetAll() on attachmentType.Id equals lineItemAttachmentType.MetattachTypeId
                    where (lineItemAttachmentType.LineItemId == lineItemId && !lineItemAttachmentType.IsDeleted && !attachmentType.IsDeleted)
                    select new AttachmentTypeDto()
                    {
                        Id = attachmentType.Id,
                        Name = attachmentType.Name
                    }).ToList();

Also, please know that Linq-to-Sql is 14x faster than Linq...

enter image description here


The answers here have covered many of the differences between Linq2Sql and EF, but there's a key point which has not been given much attention: Linq2Sql only supports SQL Server whereas EF has providers for the following RDBMS's:

Provided by Microsoft:

  • ADO.NET drivers for SQL Server, OBDC and OLE DB

Via third party providers:

  • MySQL
  • Oracle
  • DB2
  • VistaDB
  • SQLite
  • PostgreSQL
  • Informix
  • U2
  • Sybase
  • Synergex
  • Firebird
  • Npgsql

to name a few.

This makes EF a powerful programming abstraction over your relational data store, meaning developers have a consistent programming model to work with regardless of the underlying data store. This could be very useful in situations where you are developing a product that you want to ensure will interoperate with a wide range of common RDBMS's.

Another situation where that abstraction is useful is where you are part of a development team that works with a number of different customers, or different business units within an organisation, and you want to improve developer productivity by reducing the number of RDBMS's they have to become familiar with in order to support a range of different applications on top of different RDBMS's.


There are a number of obvious differences outlined in that article @lars posted, but short answer is:

  • L2S is tightly coupled - object property to specific field of database or more correctly object mapping to a specific database schema
  • L2S will only work with SQL Server (as far as I know)
  • EF allows mapping a single class to multiple tables
  • EF will handle M-M relationships
  • EF will have ability to target any ADO.NET data provider

The original premise was L2S is for Rapid Development, and EF for more "enterprisey" n-tier applications, but that is selling L2S a little short.


I found that I couldn't use multiple databases within the same database model when using EF. But in linq2sql I could just by prefixing the schema names with database names.

This was one of the reasons I originally began working with linq2sql. I do not know if EF has yet allowed this functionality, but I remember reading that it was intended for it not to allow this.


Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to entity-framework

Entity Framework Core: A second operation started on this context before a previous operation completed EF Core add-migration Build Failed Entity Framework Core add unique constraint code-first 'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync The instance of entity type cannot be tracked because another instance of this type with the same key is already being tracked Auto-increment on partial primary key with Entity Framework Core Working with SQL views in Entity Framework Core How can I make my string property nullable? Lazy Loading vs Eager Loading How to add/update child entities when updating a parent entity in EF

Examples related to linq-to-sql

Understanding SQL Server LOCKS on SELECT queries how to update the multiple rows at a time using linq to sql? LINQ: combining join and group by LINQ to SQL: Multiple joins ON multiple Columns. Is this possible? How to Select Min and Max date values in Linq Query How to do a LIKE query with linq? How to do a join in linq to sql with method syntax? How to store a list in a column of a database table Returning IEnumerable<T> vs. IQueryable<T> Entity Framework VS LINQ to SQL VS ADO.NET with stored procedures?