Since month, I'am wondering what is the difference using context.Set vs context.T instead of syntax.
I illustrate this question with this quick code that tries to get UserName from User table information from EF context.
context.Set Method
context.Set<User>().Where(u => u.Id = userId).Select(u => u.UserName).Single();
context.T Method
context.Users.Where(u => u.Id = userId).Select(u => u.UserName).Single();
Thanks :)
As Sir Rufo already pointed out, there is no difference. You can use
context.Users
because you declared a property Users
in your context class that is of type DbSet<User>
:
public DbSet<User> Users { get; set; }
In some situations you need to use context.Set<T>
because you don't know the value of T
at the time of coding , it will be set in the runtime
for example in generic Repository :
public abstract class Entity
{
public int Id { get; set; }
}
public class User:Entity
{
public string Name { get; set; }
}
public class Product:Entity
{
public string ProductName { get; set; }
}
public class ApplicationDBContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Product> Products { get; set; }
}
public class Repo<T> where T:Entity
{
public IList<T> GetList()
{
using (var context = new ApplicationDBContext())
{
return context.Set<T>().ToList();
}
}
}
then you can use GetList
with any entity as the following :
var userRepo = new Repo<User>();
var users = userRepo.GetList();
var productRepo = new Repo<Product>();
var products = productRepo.GetList();
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