dotnetcore EF many-to-many mapping
作者:互联网
class Student
{
public int Id { get; set; }
public string Name { get; set; }
public List<Teacher> Teachers { get; } = new List<Teacher>();
}
class StudentConfig : IEntityTypeConfiguration<Student>
{
public void Configure(EntityTypeBuilder<Student> builder)
{
builder.ToTable("student");
builder.Property(e => e.Name).HasColumnType("nvarchar(50)").IsRequired();
}
}
class Teacher
{
public int Id { get; set; }
public string Name { get; set; }
public List<Student> Students { get; } = new List<Student>();
}
class TeacherConfig : IEntityTypeConfiguration<Teacher>
{
public void Configure(EntityTypeBuilder<Teacher> builder)
{
builder.ToTable("teacher");
builder.Property(e => e.Name).HasColumnType("nvarchar(50)").IsRequired();
// 使用hasMany()/withMany()+指定中间表
builder.HasMany(t => t.Students).WithMany(s => s.Teachers).UsingEntity(b => b.ToTable("teacher_student"));
}
}
class MyDbContext : DbContext
{
public DbSet<Teacher> Teachers { get; set; }
public DbSet<Student> Students { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
optionsBuilder.UseLoggerFactory(loggerFactory); // output sql script to log.
//optionsBuilder.LogTo(Console.WriteLine);
optionsBuilder.UseSqlServer("Server=.;Database=demo02;Trusted_Connection=True;MultipleActiveResultSets=True");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.ApplyConfigurationsFromAssembly(this.GetType().Assembly);
}
}
class Program
{
static async Task Main(string[] args)
{
using (MyDbContext ctx = new MyDbContext())
{
await GetStudents(ctx);
}
}
private static Task GetStudents(MyDbContext ctx)
{
Student[] students = ctx.Students.Include(s => s.Teachers).Where(_ => true).ToArray();
foreach (Student s in students)
{
Console.WriteLine(s.Name);
foreach (Teacher t in s.Teachers)
{
Console.WriteLine($" {t.Name}");
}
}
return Task.CompletedTask;
}
private static async Task SaveStudentTeachers(MyDbContext ctx)
{
Student s1 = new Student { Name = "张三" };
Student s2 = new Student { Name = "李四" };
Student s3 = new Student { Name = "王五" };
Teacher t1 = new Teacher { Name = "tom" };
Teacher t2 = new Teacher { Name = "mike" };
Teacher t3 = new Teacher { Name = "jack" };
s1.Teachers.AddRange(new Teacher[] { t1, t2 });
s2.Teachers.AddRange(new Teacher[] { t2, t3 });
s3.Teachers.AddRange(new Teacher[] { t1, t2, t3 });
ctx.Students.AddRange(new Student[] { s1, s2, s3 });
await ctx.SaveChangesAsync();
}
}
标签:Name,many,builder,EF,public,dotnetcore,Student,new,Teacher 来源: https://www.cnblogs.com/mryux/p/15857340.html