How to set IdentityUser as a ForeignKey?

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

Question

This is my class briefly:

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

Then I upload a file and save the file-url to database like this way:

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

                        _dbContext.uploadFiles.Add(uploadedFile);

                        _dbContext.SaveChanges();

But in my uploadFile table 'userId' column is always null. I am new comer to ASP.NET Core, can you tell me what is going wrong with my code? Thank you very much!

enter image description here

1
1
12/28/2018 4:20:33 PM

Popular Answer

Write your UploadFile model as follows:

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

Then in the DbConext configuration.

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

Now run a brand new migration!

And modify your FileUpload method code as follows:

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 how to get current logged in UserId then Here it is

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