简体   繁体   中英

Entity Framework relationship to IdentityUser not resolving

I have a class named "MyFile" that has a Many-to-One relationship to "Workspace" and then the "Workspace" has a Many-to-One relationship to "IdentityUser". This works well when I create a Workspace the relationship to the IdentityUser is configured correctly, however when I fetch the Workspace the Owner field show up as null. In the database the value is set in the Owner column.

So what I want to do is get a list of All Files and whom they belong to, but since the Owner property is null I'm not able to figure out the owner. Database wise all looks good. (This code has been simplified to focus on the problem)

public class MyFile
{
    // Base
    public Guid MyFileID { get; set; }

    [Column(TypeName = "nvarchar(256)")]
    public string Name { get; set; }
    
    // Workspace
    public virtual Workspace Workspace { get; set; } 
}


public class Workspace
{
    // Base
    public Guid WorkspaceID { get; set; }
    public string Name { get; set; }

    // Security
    public virtual IdentityUser Owner { get; set; }
}

Code to get the information that ends up with Owner = Null:

        var myFiles = _applicationDbContext.MyFiles
            .Include(x => x.Workspace)
            .ThenInclude(y => y.Owner)
            .Where(x => x.Deleted == showDeleted)
            .OrderByDescending(x => x.Uploaded)
            .Skip(pagesize*(page-1))
            .Take(pagesize);

I managed to solve the issue by extending the IdentityUser class with ApplicationUser and then change the relationship to ApplicationUser instead. Also i added a ApplicationUserId which I populate at the same time as I Populate the ApplicationUser then I could use to lookup the correct IdentityUser in my lamdba. There is probably a better solution but this worked for me.

public class Workspace
{
    // Base
    public Guid WorkspaceID { get; set; }
    public string Name { get; set; }

    // Security
    public string ApplicationUserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
}

Extension Class:

public class ApplicationUser : IdentityUser
{
}

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