Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using DbContext Set<T>() instead of exposing on the context

Are there any differences when doing the following:

public class UsersContext : DbContext {     public DbSet<User> Users { get; set; } } 

versus using the Set<T> method of the context:

public class UsersContext : DbContext { }  var db = new UsersContext(); var users = db.Set<User>(); 

These effectively do the same thing, giving me a set of Users, but are there any big differences other than you are not exposing the set through a property?

like image 509
Dismissile Avatar asked Dec 04 '12 19:12

Dismissile


People also ask

What does DbContext set do?

Set(Type) Returns a non-generic DbSet instance for access to entities of the given type in the context and the underlying store.

Should you use using with DbContext?

EF and EF Core DbContext types implement IDisposable . As such, best practice programming suggests that you should wrap them in a using() block (or new C# 8 using statement). Unfortunately, doing this, at least in web apps, is generally a bad idea.

How does DbContext change state of entity?

This can be achieved in several ways: setting the EntityState for the entity explicitly; using the DbContext. Update method (which is new in EF Core); using the DbContext. Attach method and then "walking the object graph" to set the state of individual properties within the graph explicitly.


1 Answers

The Users property is added for convenience, so you don't need to remember what all of your tables are and what the corresponding class is for it, you can use Intellisense to see all of the tables the context was designed to interact with. The end result is functionally equivalent to using Set<T>.

like image 95
Servy Avatar answered Sep 22 '22 14:09

Servy