代码改变世界

The EF4 Sample

2011-12-19 10:15  barbarossia  阅读(128)  评论(0编辑  收藏  举报

The Entity Framework 4.0 is a powful framework that used by entity to SQL. Here is a sample explain the many-to-many relationship.

The relationship is user and role. The User_Role is the table that save the relationship between user and role.

Some code snipes are :

        public void UpdateUser(DC.User user)
{
using (var context = GetContext())
{
var existUser = Get(context, user.Id);
if (existUser == null)
throw new ApplicationException(string.Format("Update failed, user id: {0} didn't exist.", user.Id));
UpdateUser(context, existUser, user.FromDataContract());
//update roles
UpdateRoles(context, user);
context.SaveChanges();
}
}

private void UpdateUser(SampleDBEntities context, User existUser, User user)
{
context.Users.Detach(existUser);
context.Users.Attach(user);
context.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
}

private void UpdateRoles(SampleDBEntities context, DC.User user)
{
var updateUser = Get(context, user.Id);
var roles = user.Roles.FromDataContract();
var intersectRoles = updateUser.Roles.Select(r => r.Id).Intersect(roles.Select(r => r.Id)).ToList();
var removeRoles = updateUser.Roles.Select(r => r.Id).Except(intersectRoles).ToList();
foreach (var roleId in removeRoles)
{
var oldRole = GetRole(context, roleId);
if (oldRole == null)
throw new ApplicationException(string.Format("Update failed, role id: {0} didn't exist.", roleId));
updateUser.Roles.Remove(oldRole);
}

var addRoles = roles.Select(r => r.Id).Except(intersectRoles).ToList();
foreach (var roleId in addRoles)
{
var newRole = GetRole(context, roleId);
if (newRole == null)
throw new ApplicationException(string.Format("Update failed, role id: {0} didn't exist.", roleId));
updateUser.Roles.Add(newRole);
}
}


 The full code is here.