Search code examples
c#genericsasp.net-mvc-5entity-framework-6asp.net-identity

Convert or Create TUser in UserStore From a DbObject in Asp.net mvc 5 Identity "Connot Implicitly convert type"


I am new to Asp.Net Identity, and working on creating my own UserStore, but cannot get TUser to play. I have EntityFramework6 database first in the back end, and I am getting data from there no problem. My issue is converting the object I get from EF6 to TUser. I'll walk you through what I have.

1) AccountController calls PasswordSignInAsync in signInManager

_signInManager.PasswordSignInAsync(LoginAuditLog);

2) Call FindByNameAsync in my user manager

await this.UserManager.FindByNameAsync(LoginAuditLog.UserName); 

3) then in my UserStore I have

  public Task<TUser> FindByNameAsync(string userName)
    {
        return Task.FromResult(_userTable.Login(userName));
    }

4) When it gets to _userTable.Login() it make the call to the Db and return the object i want, but getting the object to convert to TUser is my issue.

    public TUser Login(string userName)
    {
        TUser y = _unitOfWork.WebPortalUsers.FindByUserName(userName);

        return y;
    }

I have tried casting, converting and other stuff from internet searches. I am getting Connot Implicitly convert type and if I cast or convert I just get the runtime version of this error. Snip of error message


Solution

  • Your method FindByUserName returns WebPortalUser type of instance while you are implicitly assigning it to TUser. You either need to cast it to TUser if both types are having parent child relationship like:

     TUser y = _unitOfWork.WebPortalUsers.FindByUserName(userName) as TUser;
    
     return y;
    

    or if that's not the case then you will need to create an instance and set the required properties explicitly or use a mapper like AutoMapper but for that the type of the properties in both classes should be same:

    var user = _unitOfWork.WebPortalUsers.FindByUserName(userName);
    
    TUser y = new TUser();
    y.Username = user.Username;
    .....
    .....
    // other properties
    

    Hope it gives some idea.