many to many ef core example
Example 1: ef core many-to-many
class MyContext : DbContext
{
public MyContext(DbContextOptions options)
: base(options)
{
}
public DbSet Posts { get; set; }
public DbSet Tags { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasMany(p => p.Tags)
.WithMany(p => p.Posts)
.UsingEntity(
j => j
.HasOne(pt => pt.Tag)
.WithMany(t => t.PostTags)
.HasForeignKey(pt => pt.TagId),
j => j
.HasOne(pt => pt.Post)
.WithMany(p => p.PostTags)
.HasForeignKey(pt => pt.PostId),
j =>
{
j.Property(pt => pt.PublicationDate).HasDefaultValueSql("CURRENT_TIMESTAMP");
j.HasKey(t => new { t.PostId, t.TagId });
});
}
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public ICollection Tags { get; set; }
public List PostTags { get; set; }
}
public class Tag
{
public string TagId { get; set; }
public ICollection Posts { get; set; }
public List PostTags { get; set; }
}
public class PostTag
{
public DateTime PublicationDate { get; set; }
public int PostId { get; set; }
public Post Post { get; set; }
public string TagId { get; set; }
public Tag Tag { get; set; }
}
Example 2: one to many relationship ef core
// 1:M
// ONE company has MANY employees
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
public ICollection Employees { get; set; }
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public Company Company { get; set; }
}