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 ?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With