代码之家  ›  专栏  ›  技术社区  ›  Greg Hunt

从数据库加载自定义ApplicationUser对象

  •  1
  • Greg Hunt  · 技术社区  · 7 年前

    IdentityUser 类进入 ApplicationUser

    namespace TxTools.Data.Features.Shared.Models
    {
        public class ApplicationUser : IdentityUser
        {
            public string FirstName { get; set; }
    
            public string LastName { get; set; }
            [ForeignKey("PhotoResourceId")]
            public BlobResource Photo { get; set; }
        }
    }
    

    这是我的 BlobResource

    namespace TxTools.Data.Features.BlobStorage.Models
    {
        public class BlobResource
        {
            [Key]
            public Guid ResourceId { get; protected set; }
            public string Container { get; protected set; }
            public string MimeType { get; protected set; }
            public string Filename => String.Format("{0}.{1}", ResourceId, MimeTypes.GetExtension(MimeType));
            public BlobResource(string container, string mimeType)
            {
                this.ResourceId = Guid.NewGuid();
                this.Container = container;
                this.MimeType = mimeType;
            }
        }
    }
    

    实体框架保存 水滴源 当我将其添加到 应用程序用户 水滴源

    1 回复  |  直到 7 年前
        1
  •  0
  •   user3456014 user3456014    7 年前

    User BlobResource 类需要相互引用。您需要确定关系是一对一(一个用户一张照片)、一对多(一个用户多张照片或多个用户一张照片)还是多对多。

    https://docs.microsoft.com/en-us/ef/core/modeling/relationships

    其次,EF是延迟加载,因此当您从数据库加载用户时,必须告诉它跟踪这些关系。假设您有一个扩展的DB上下文类 IdentityDbContext

    public class MyContext: IdentityDbContext<ApplicationUser>
    {
        public DbSet<ApplicationUser> Users { get; set; }
        public DbSet<BlobResource> BlobResources { get; set; }
    }
    

    ... 你会使用 Include 具体如下:

    var usersWithBlobs = myContext.Users.Include(user => user.Photo);
    

    id :

    var myUser = myContext.Users.Where(u => u.Id == id).Include(user => user.Photo);
    

    此处描述了加载: https://docs.microsoft.com/en-us/ef/core/querying/related-data