从数据库

时间:2017-09-29 18:58:59

标签: c# entity-framework asp.net-core entity-framework-core asp.net-core-identity

我正在使用带有身份和实体框架的ASP.NET Core 2.0。我已将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;
        }
    }
}
当我将BlobResource添加到ApplicationUser时,

实体框架会保存BlobResource,但我无法从数据库加载"ts"。该对象始终为null。我已经尝试了几个Fluent API命令来尝试加载它,但没有一个工作。

1 个答案:

答案 0 :(得分:0)

首先,UserBlobResource类需要相互引用。您需要确定关系是一对一(一个用户一张照片),一对多(一个用户多张照片,或许多用户一张照片)还是多对多关系。

实体框架描述关系的方式在这里:https://docs.microsoft.com/en-us/ef/core/modeling/relationships

其次,EF是延迟加载的,所以当你从数据库加载用户时,你必须告诉它追逐这些关系。假设您有一个扩展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

相关问题