在EntityFramework CodeFirst中过滤DbSet

时间:2017-01-10 07:13:30

标签: c# asp.net-mvc entity-framework dbcontext

这是ApplicationUser:

public class ApplicationUser : IdentityUser<long>
{
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public UserTypes Type { get; set; }
    public string FullName { get { return $"{Firstname ?? ""} {Lastname ?? ""}".Trim(); } }
}

我们有3种不同的UserTypes(Provider,Supporter,NormalUser (这是ApplicationUser)

public class Provider : ApplicationUser{
   // Provider related virtual Icollections
}

public class Supporter : ApplicationUser{
   // Supporter related virtual Icollections
}

现在在ApplicationDbContext我希望在ApplicationUser旁边有这些DbSet

public virtual DbSet<Provider> Providers{get;set;}
public virtual DbSet<Supporter> Supporters{get;set;}

哪个DbSet<Provider>应该返回ApplicationUsers UserTypes等于2(例如)

1 个答案:

答案 0 :(得分:1)

     public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole<long>, long>
        {

            public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
                : base(options)
            {
            }
            public ApplicationDbContext()
                : base()
            {
            }

            public virtual IEnumerable<Provider> Providers
            {
                get
                {
                    return (IEnumerable<Provider>)Users.Where(z => z.Type == UserTypes.Provider).AsEnumerable();
                }
            }
         }