1

I use "AspIdentity" in the project. In project all standard models of "AspIdentity" and one model "Post". I would like each post to have its ApplicationUser and each ApplicationUser have its own collection of posts. And already have one database in which there is a table that stores information about users.

I tried to create tables, data context and database independently, but I don't find any information but I didn't find information about the case close to mine.

Post model:

public class Post
{
    public int Id { get; set; }
    public string Body { get; set; }
    public string ApplicationUserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
}

ApplicationUser model:

public class ApplicationUser : IdentityUser
{
    public int Year { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
    public ApplicationUser()
    {
        Posts = new List<Post>();
    }
}

I expect to see a data context in the response and a query with which to create a table of posts.

pfx
  • 20,323
  • 43
  • 37
  • 57
  • Have you seen this: https://stackoverflow.com/questions/20104289/foreign-key-to-microsoft-aspnet-identity-entityframework-identityuser – Adam Jachocki Jan 11 '19 at 11:32
  • The point would be in which DbContext they are mapped. If you have a separate BlogContext and ApplicationContext then I don't think EF will let you map this. Even if SQL has no problem with it (cross database). – bommelding Jan 11 '19 at 11:48

1 Answers1

0

You need to override the OnModelCreating method in your DbContext class (presumably ApplicationDbContext). In the overridden method, establish the relationship between the classes. The following is the sample code that should solve your problem:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<ApplicationUser>()
                .HasMany(e => e.Posts)
                .WithRequired(e => e.ApplicationUser)
                .HasForeignKey(e => e.ApplicationUserId)
                .WillCascadeOnDelete(false);
}
Tanveer Yousuf
  • 386
  • 1
  • 3
  • 16