Entity Framework: When to use Set<>

c# entity-framework

Question

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?

1
15
6/7/2013 12:48:36 PM

Accepted Answer

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.

12
6/7/2013 12:52:06 PM

Popular Answer

The only reason i have ever used Set<T> is when you are acting on a type you dont know, eg a generic insert.

Heres an example from my generic repository:

  public void AddOnSave(T entity)
  {
     ctx.Set<T>.Add(entity);
  }

Using it for regular stuff just makes the code less readable IMHO



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow