Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF - context.Set<t> vs context.T

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

like image 648
OrcusZ Avatar asked Mar 16 '17 09:03

OrcusZ


2 Answers

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; }
like image 198
Loetn Avatar answered Sep 17 '22 18:09

Loetn


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();
like image 33
Cyber Progs Avatar answered Sep 19 '22 18:09

Cyber Progs