A simple example, User is many to many relationship with Role, 

in database view, there are 3 tables, tbl_user,tbl_role, tbl_user_role

Implement of save user method,when using Nhibernate, you can write like this:


 1 usr = new user();
 2 
 3 usr.username="GuGu is best";
 4 
 5 usr.roles.add(new role(){roleid=1}); 
 6 //if db has exist roleid=1 record, will use existed one,
 7 but linq2sql will occur exception
 8 
 9 usr.roles.add(new role(){roleid=2});
10 
11 // write a custom base class Repository
12 Repository.Save(usr);
13 
14 //it will generate sql for insert/update tbl_user and tbl_user_role


 

but for linq2sql, you must write more ugly:

 1 using (myDataContext db = new myDataContext())
 2             {
 3 
 4                if (IsAddNew)      //you must manual judge whether insert or update         
 5                 {
 6                     db.Users.InsertOnSubmit(usr);
 7                 }
 8                 else
 9                 {
10 
11         //if you use rowversion,just like this, or assign usr's fields value to existUsr one by one
12 
13            var existUsr =db.Users.ByUserID(usr.UserID).FirstOrDefault();
14                     if(existUsr!=null)
15                         usr.Version = existUsr.Version;
16                     db.Users.Attach(usr, true);
17                 }
18                 db.SubmitChanges();
19             }


 if you want to delete a user, but there are FK reference to it, in linq2sql, you should manual delete the many to many object,

 


using (myDataContext db =new myDataContext())
{
     db.UserRoles.DeleteAllOnSubmit(
db.UserRoles.Where(t 
=> t.UserID == userID));
     db.Users.Delete(userID);
     db.SubmitChanges();
}


 

 

posted on 2010-12-29 15:46  Gu  阅读(207)  评论(0编辑  收藏  举报