Here's an example of using the user table and the project table
There is such a requirement:
The relationship between the user and the project is that a user can send multiple projects, can participate in multiple projects, and the project can have multiple participating members and one publisher
Project structure:
The entity class structure is designed as follows
<summary>///user// </summary> public class User {public int ID {get;set;} public string Nickname {get; set;} Public DateTime registertime {get; set;} <summary>//// participation in the list/// </summary> public icollection<project> Projects {get; Set } }
<summary>///project/// </summary> public class project {public int ID {get; set ; Public string Title {get; set;} public string Description {get; set;} <summary>///Project Publisher/// </summary> public virtual User founder {get; set;} <summary>///participating Members/// </summary> public virtual icollection<user> Member {get; Set } }
Then, create a new mapping class UserMap
public class usermap:entitytypeconfiguration<user> {public UserMap () {//define a many-to-many relationship between user and project this . hasmany<project> (U = u.projects). Withmany (P=>p.member); } }
In the EF context
Public class Db:dbcontext {public DB (): Base ("DefaultConnection") {} public dbset<user> User { Get Set Public dbset<project> Project {get; set;} protected override void Onmodelcreating (Dbmodelbuilder modelBuilder) { modelbuilder.conventions.remove< Pluralizingtablenameconvention> ();//Remove the contract//base of the plural table name . Onmodelcreating (ModelBuilder); MODELBUILDER.CONFIGURATIONS.ADD (New UserMap ()); } }
Class program { static void Main (string[] args) { db db = new DB (); Db. User.tolist (); Console.readkey (); } }
After running, the table structure
"EF Code First" multi-to-many relationship configuration