How to set IdentityUser as a ForeignKey?

asp.net-core c# entity-framework-core

Popular Answer

Publish yourUploadFile model like this:

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`
}

Next, in theDbConext configuration.

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

Run a fresh migration now!

And then change the code for your FileUpload function to read:

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();

Note: If you need to know how to log in right nowUserId next This is it.

0
12/28/2018 4:17:32 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow