Asp.net Core - One-to-many relationship between IdentityUser class and custom defined class

I have a problem with a navigation property that cannot be matched, I have an ID use class as below:

public partial class User: IdentityUser
{
    public User() : base()
    {
        this.Blog= new HashSet<Blog>();
    }

    public string Nom { get; set; }
    public string Prenom { get; set; }
    public virtual ICollection<Blog> Blogs{ get; set; }
}

      

And the Blog class, for example, is the following:

public partial class Blog : BaseModel
{        
    public string UserId { get; set; }
    public virtual User User{ get; set; }
}

      

In IdentityDbContext, I have overridden the OnModelCreating method as follows:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Blog>()
        .HasOne(b => b.User)
        .WithMany(u => u.Blogs);
}

      

Laid out a database with user data as follows:

var usr1 = new User()
{
    Email = "colab1@emai.l",
    Nom = "CollaborateurNom",
    Prenom = "CollaborateurPrenom"
};
var userResult = await usrMgr.CreateAsync(usr1, "P@ssw0rd!");

Blog blg1 = new Blog()
{
    User = usr1
};

await ctx.SaveAsync();

      

In the database, I am getting the User attribute on the blog as null, I know I was missing something, just don't know what exactly, please help!

[UPDATE]

Recently noticed that this could be due to the asynchronous creation of User rows in the database, perhaps trying to add a user who is not yet in the database, but still does not know how to make sure that the user is already in the database data before trying to assign it to a blog post.

+3


source to share





All Articles