Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Data.Entity.DbSet vs System.Data.Entity.Infrastructure.DbQuery

Can someone please explain whats the difference between the two in Entity Framework.

Example1:

obj = new TicketsEntities();
var depts = obj.DEPARTMENTs.Select( x => x);
string str = depts.GetType().ToString();

In this case str prints --- System.Data.Entity.Infrastructure.DbQuery`1[LINQu.Models.DEPARTMENT]

Example2:

obj = new TicketsEntities();
var depts = obj.DEPARTMENTs;
string str = depts.GetType().ToString();

In this case str prints --- System.Data.Entity.DbSet`1[LINQu.Models.DEPARTMENT]

In either case when we loop through the depts we get same result , so what is the difference between the two , and which one is preferred ?

like image 205
refactor Avatar asked Sep 28 '14 04:09

refactor


People also ask

What is DbSet in Entity Framework?

A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext. Set method.

What is DBQuery?

DBQuery is a non-generic LINQ to Entities query against a DbContext. Exposing this will give you LINQ functionality against Entities. If you don't need this, use the IQueryable interface abstraction. IOrderedQueryable. Intended for implementation by query providers.

Which of the following type is derived from DbSet class in Entity Framework?

DbSet in Entity Framework 6. The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views.


1 Answers

The DbSet represents the set of data and can manipulate the data by exposing methods like Add, Update, Remove. The DbQuery represents a Linq query that is executed on a set of data. It does not have the Add, Update and Remove methods.

In your case I think there is no real difference, but for simplicity sake I would pick your second example since the Select(x=>x) is not neccessary.

like image 150
Martien de Jong Avatar answered Sep 24 '22 04:09

Martien de Jong