Many-to-many relations of entityframework (IV.)

Source: Internet
Author: User
Tags connectionstrings

The previous article describes a one-to-many relationship, the following describes the next many-to-many relationship code writing.

1, the new model entity, user is the users class, role is a character class, because it is a many-to-many relationship, there must be an intermediate class, so produced the Userrole class

1      Public classUser2     {3          Public intId {Get;Set; }4          Public stringName {Get;Set; }5 6          Public VirtualIcollection<userrole> Userroles {Set;Get; }7     }8 9      Public classRoleTen     { One          Public intId {Get;Set; } A          Public stringName {Get;Set; } -  -          Public VirtualIcollection<userrole> Userroles {Set;Get; } the     } -  -      Public classuserrole -     { +          Public intId {Get;Set; } -          Public intUId {Get;Set; } +          Public intRId {Get;Set; } A  at          Public VirtualUser User {Set;Get; } -          Public VirtualRole role {Set;Get; } -}

2. Create a entitycontext and inherit from DbContext

1      Public classEntitycontext:dbcontext2     {3          PublicEntitycontext ()4:Base("name=dbconnectionstring")5         {6 7         }8 9          PublicDbset<user> User {Get;Set; }Ten          PublicDbset<role> Role {Get;Set; } One          PublicDbset<userrole> Userrole {Get;Set; } A  -         protected Override voidonmodelcreating (Dbmodelbuilder modelBuilder) -         { the modelBuilder.Configurations.AddFromAssembly (assembly.getexecutingassembly ()); -             Base. Onmodelcreating (ModelBuilder); -         } -}

3. Add the database connection string in the Web. config file

1   < connectionStrings > 2     <  name= "dbconnectionstring"  connectionString= "Data source=.;i Nitial catalog=manytomany;integrated security=true "  providerName=" System.Data.SqlClient "  />3   </connectionStrings>

4. Then create the Entity mappings

1      Public classUsermap:entitytypeconfiguration<user>2     {3          PublicUserMap ()4         {5ToTable ("User");6Haskey (U =u.id);7         }8     }9 Ten      Public classRolemap:entitytypeconfiguration<role> One     { A          PublicRolemap () -         { -ToTable ("Role"); theHaskey (R =r.id); -         } -     } -  +      Public classUserrolemap:entitytypeconfiguration<userrole> -     { +          PublicUserrolemap () A         { atToTable ("userrole"); -Haskey (ur =Ur. ID); -  -             //Willcascadeondelete: Do not use cascade delete -Hasrequired (pt = pt. User). Withmany (p = p.userroles). Hasforeignkey (pt = pt. UID). Willcascadeondelete (false); -  inHasrequired (pt = pt. Role). Withmany (t = t.userroles). Hasforeignkey (pt = pt. RID). Willcascadeondelete (false); -         } to}

5, we write some operations, let code first build the database and verify that the data is new

1     varuser =NewUser () {Name ="Bob" };2Db. Set<user>(). ADD (user);3 4     varRole =NewRole () {Name ="Admin" };5Db. Set<role>(). ADD (role);6 7 db. SaveChanges ();8 9     varur =NewUserrole () {RId = role. Id, UId =user. ID};TenDb. Set<userrole>(). ADD (UR); One db. SaveChanges (); A  -     //var list = db. Set<user> (). Include ("Userroles"). ToList (); -     //If you need to find out what role userroles under, the     //avoid the need to access the database through lazy loading (the same foreign key entity will only be accessed once, but more still in the following ways) -     varList = db. Set<user> (). Include ("Userroles.role"). ToList ();

6. Database diagram

Many-to-many relations of entityframework (IV.)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.