The EF4.1 Sample
2011-12-19 10:20 barbarossia 阅读(179) 评论(0) 收藏 举报The Entity Framework 4.1 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(User user)
{
UpdateUsers(user);
UpdateRoles(user);
}
private void UpdateUsers(User user)
{
using (var context = GetContext())
{
context.Users.Attach(user);
context.Entry(user).State = EntityState.Modified;
context.SaveChanges();
}
}
private void UpdateRoles(User user)
{
using (var context = GetContext())
{
var userToUpdate = GetUser(context, user.Id);
if (userToUpdate == null)
throw new ApplicationException(string.Format("Update failed, user id: {0} didn't exist.", user.Id));
var roles = user.Roles;
var intersectRoles = userToUpdate.Roles.Select(r => r.Id).Intersect(roles.Select(r => r.Id)).ToList();
var removeRoles = userToUpdate.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));
userToUpdate.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));
userToUpdate.Roles.Add(newRole);
}
context.SaveChanges();
}
}
The full code is here.
The improve version code is add the enum that indicate the action of insert or modify.
public enum ActionCode
{
Inserted,
Updated,
Deleted
};
After improve code is:
private void UpdateProducts(Category category)
{
using (var context = GetContext())
{
var categoryToUpdate = GetCategory(context, category.CategoryId);
if (categoryToUpdate == null)
throw new ApplicationException(string.Format("Update failed, user id: {0} didn't exist.", category.CategoryId));
foreach (var productToUpdate in category.Products)
{
switch (productToUpdate.ActionCode)
{
case ActionCode.Inserted:
productToUpdate.Category = categoryToUpdate;
context.Products.Add(productToUpdate);
break;
case ActionCode.Updated:
var oldProduct = GetProduct(context, productToUpdate.ProductId);
context.Entry(oldProduct).CurrentValues.SetValues(productToUpdate);
break;
case ActionCode.Deleted:
if (context.Entry(productToUpdate).State == EntityState.Detached)
context.Products.Attach(productToUpdate);
context.Products.Remove(productToUpdate);
break;
}
}
context.SaveChanges();
}
}
The full code is here.
浙公网安备 33010602011771号