Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework: When to use Set<>

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?

like image 514
Serberuss Avatar asked Jun 07 '13 12:06

Serberuss


People also ask

What is DbSet <>?

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.

What is entity set in Entity Framework?

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.)

What is meant by DbContext and DbSet?

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.

What difference does AsNoTracking () make?

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.


1 Answers

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.

like image 56
Dennis Avatar answered Oct 05 '22 19:10

Dennis