如何将IdentityUser设置为ForeignKey?

时间:2018-12-28 14:54:59

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

这是我的课程简述:

public class UploadFile
{

    public int Id { get; set; }
    public TinyBlog2User User { get; set; } //this user is extend from IdentityUser
    public byte[] md5 { get; set; }
    public string Uri { get; set; }
    public string ThumbnialUri { get; set; }
}

然后我上传文件,并将文件URL像这样保存到数据库:

 UploadFile uploadedFile = new UploadFile()
                        {
                            md5 = md5Value,
                            Uri = fileBlob.Uri.ToString(),
                            User = currentUser,
                            ThumbnialUri = thumbnailBlob.Uri.ToString()
                        };

                        _dbContext.uploadFiles.Add(uploadedFile);

                        _dbContext.SaveChanges();

但是在我的uploadFile表的'userId'列中始终为null。 我是ASP.NET Core的新手,您能告诉我我的代码出了什么问题吗? 非常感谢你!

enter image description here

2 个答案:

答案 0 :(得分:0)

在IdentityUser的扩展范围内

List<UploadFile> UploadFile {get; set;}

并在上传文件中

public int UserId {get; set;}

在此键入用户表的ID类型和属性名称应为TableName + Id

答案 1 :(得分:0)

编写您的UploadFile模型,如下所示:

public class UploadFile
{

    public int Id { get; set; }
    public string UserId { get; set; } 
    public byte[] md5 { get; set; }
    public string Uri { get; set; }
    public string ThumbnialUri { get; set; }

    public ApplicationUser ApplicationUser { get; set; } //this user is extend from `IdentityUser`
}

然后以DbConext配置。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
     modelBuilder.Entity<UploadFile>()
            .HasOne(uf => uf.ApplicationUser)
            .WithMany()
            .HasForeignKey(uf => uf.UserId);
}

现在运行全新的迁移!

并如下修改您的FileUpload方法代码:

UploadFile uploadedFile = new UploadFile()
                    {
                        md5 = md5Value,
                        Uri = fileBlob.Uri.ToString(),
                        UserId = currentUser.Id, // Here set the current logged in UserId
                        ThumbnialUri = thumbnailBlob.Uri.ToString()
                    };

                    _dbContext.uploadFiles.Add(uploadedFile);

                    _dbContext.SaveChanges();

注意:如果您需要如何获取UserId上的当前登录信息,那么Here it is