I'm trying understand the basics of Entity Framework and I have a question about the Set<> method on DbContext. I am using a database first model for the following question.
Let's say I have an ActivityLog database which amongst other things I can use to pull out a message (NLog message, for example). I could write some code to pull out all messages like this:
using (var entities = new ActivityLogEntities())
foreach (var log in entities.AcitivityLogs)
Console.WriteLine(log.Message);
However I could also achieve the same thing doing this:
using (var entities = new ActivityLogEntities())
foreach (var message in entities.Set<ActivityLog>().Select(entity => entity.Message))
Console.WriteLine(message);
My question is what is the difference between these two statements? When is it more appropriate to use one over the other? Or is this just a matter of personal preference?
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.
An entity set is a logical container for instances of an entity type and instances of any type derived from that entity type. (For information about derived types, see Entity Data Model: Inheritance.)
DbContext generally represents a database connection and a set of tables. DbSet is used to represent a table. Your code sample doesn't fit the expected pattern.
AsNoTracking() . This optimisation allows you to tell Entity Framework not to track the results of a query. This means that Entity Framework performs no additional processing or storage of the entities which are returned by the query.
There's no significant difference. In the first case, you have something like:
class MyContext : DbContext
{
public DbSet<AcitivityLog> AcitivityLogs { get; set; }
}
When context is creating, it looks for public DbSet<T>
read/write-properties, and does this (pseudo-code):
dbSetProperty = Set<EntityType>();
But, there are cases, when you:
1) don't want to make public properties for all of you entity types;
2) don't know all of the entity types at context's design time.
In these cases Set<T>
is the only way to get proper entity set.
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