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!
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