I have a many to many relation and I am using ASP.Net Core2.2 MVC with EF.
From what I read I understand that at the current time I have to create a CLR class for join table.
My code:
Models:
public class Post
{
public Post()
{
Categories= new List<PostCategory>();
}
public int Id { get; set; }
[Required]
public string Title { get; set; }
[Required]
public string Description { get; set; }
public List<PostCategory> Categories { get; set; }
}
public class Category
{
public Category()
{
Posts= new List<PostCategory>();
}
public int Id { get; set; }
[Required]
public string Name { get; set; }
public ICollection<PostCategory> Posts { get; set; }
}
public class PostCategory
{
public int PostId { get; set; }
public Post Post { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
DBContext:
public class MyDBContext:DbContext
{
public MyDBContext()
{
}
public MyDBContext(DbContextOptions<MyDBContext> options) : base(options)
{
}
public DbSet<Post> Post { get; set; }
public DbSet<Category> Category { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<PostCategory>()
.HasKey(x => new { x.PostId, x.CategoryId });
modelBuilder.Entity<PostCategory>()
.HasOne(x => x.Post)
.WithMany(m => m.Categories)
.HasForeignKey(x => x.PostId);
modelBuilder.Entity<PostCategory>()
.HasOne(x => x.Category)
.WithMany(e => e.Posts)
.HasForeignKey(x => x.CategoryId);
}
}
Create Post Code:
var categories= new List<PostCategory>();
foreach (var category in model.SelectedCategories)
{
categories.Add(new PostCategory()
{
CategoryId= category
});
}
model.Post.Categories.AddRange(categories);
_context.Post.Add(model.Post);
await _context.SaveChangesAsync();
When I create a post I can see in database that I have Post data, and in PostCategory table I can see PostId CategoryId as they should be.
My issue is when I try to get a post data using:
var post = await _context.Post.FindAsync(id);
post.Categories count is always 0, what am I missing?
You need to write your query as follows to eager load the related Categories
with Post
:
var post = await _context.Post.Include(p => p.Categories).FirstOrDefaultAsync(p => p.Id == id);
Here is the more details about Loading Related Data in EF core
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With