简体   繁体   中英

Find user by custom property identity asp.Net mvc

I am trying to find an user that has a custom property "Token" that I added with database migration, I tried to use:

var adb = new AppDbContext();
var found = adb.Users.Where(u => u.Token == "ABDJ_SJ_ETC");//Error
//OR found = adb.Users.SingleOrDefault(); Error too

My AppDbContext class

AppDbContext.cs

namespace MyApp{
    public class AppDbContext : IdentityDbContext<AppUser>{
         public AppDbContext(): base("DefaultConnection"){}
    }
}

AppUser.cs

namespace MyApp{
    public class AppUser : IdentityUser{
        public string Token {get;set;}
    }
}

The error is "System.Data.Entity.IDbSet does not contain a definition for 'Where' and no extension method 'Where' accepting a first argument of type 'System.Data.Entity.IDbSet could be found (are you missing a using directive or an assembly reference?)

Without the Where line my app runs correctly, add Users to db with my Token, etc. What i need to do to find an AppUser by that custom field??

In Visual Studio, you can rollover the error line and it will suggest the appropriate missing using .

Remember to included in your code the .SingleOrDefault() statement in line:

var found = adb.Users.Where(u => u.Token == "ABDJ_SJ_ETC").SingleOrDefault()

The problem was that Visual Studio didn't suggest me any dependencies to resolve, and i didn't know which directive needed to use,

I added

using System.Linq;

and that solved the problem

Thanks @pswg for helping me

use bottom code for get custom ApplicationUser in identity with custom property

var context=new AuthContext();
var result=context.Users.OfType<ApplicationUser>.SingleOrDefault(item => item.NationalCode == "");

NationalCode is custom property in ApplicationUser ApplicationUser is custom user that implement IdentityUser

public class ApplicationUser :  IdentityUser
{
    public string NationalCode { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM