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?
Set(Type) Returns a non-generic DbSet instance for access to entities of the given type in the context and the underlying store.
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.
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.
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>
.
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