ADO.NET Entity Framework Many-to-Many

Jika ada tabel many-to-many, dengan tabel perantara yang tidak memiliki id, perlu penanganan khusus pada DbContext. Contoh penanganan sbb:

[code language=”csharp”]
public class SchoolContext : DbContext
{
public DbSet<Course> Courses { get; set; }
public DbSet<Person> People { get; set; }

public SchoolContext()
: base("MyDb")
{
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Course>().
HasMany(c => c.Students).
WithMany(p => p.CoursesAttending).
Map(
m =>
{
m.MapLeftKey("CourseId");
m.MapRightKey("PersonId");
m.ToTable("PersonCourses");
});

}
}
[/code]

http://www.codeproject.com/Articles/234606/Creating-a-Many-To-Many-Mapping-Using-Code-First

Chandra Oemaryadi has written 244 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>