Dmitry Dmitry - 3 months ago 5
C# Question

Many to Many relation in EF made without links to the entity

I would like to shift from the common pattern in many to may relation using implicit joint table and instead I want to use the joint table explicitely and implement a kind of lazy load of many-to-many dependent entity.

This is framed by the design of disconnected sets, where the objects graph is passed via http to the application server. On the server I update just keys, not entities.
The reason for that: if I try to save the same entity defined with different instances of an entity model, I get the concurrent scenario error.
Instead, I don't want to pass on object, rather I just want to pass the joint table with IDs.

Class
-------
int ID
List ClassStudent

Student
-------
int ID
List ClassStudent


ClassStudent // this type must be explicitely defined in the model
--------------
StudentID
ClassID


Is it possible to define such configuration with FluentApi?

The common scenarion is using types:

Student
---------------
int ID
List Classes

Class
----------
int ID
List Students


I don't need this beacuse of concurrent changes.
Need to help with fluent API. I've tried many cases.

Answer

Yes, it's possible. All you need is to configure a composite PK for the ClassStudent and two unidirectional one-to-many relationships (Student -> ClassStudent and Class -> ClassStudent).

Something like this:

modelBuilder.Entity<ClassStudent>
    .HasKey(e => new { e.StudentID, e.ClassID });

modelBuilder.Entity<Student>
    .HasMany(e => e.ClassStudent)
    .WithRequired()
    .HasForeignKey(e => StudentID);

modelBuilder.Entity<Class>
    .HasMany(e => e.ClassStudent)
    .WithRequired()
    .HasForeignKey(e => ClassID);
Comments