避免过多的控制流在MVC中使用Id数组

时间:2015-09-21 15:17:29

标签: c# asp.net-mvc entity-framework

MVC中的多选列表似乎与复杂模型绑定。相反,它们返回一组选定的Id编号。

我在页面上有这样的控件,我对为了让它工作而必须部署的条件逻辑的数量感到恼火。有问题的对象是一个Staff对象,其TeamMember成员资格可以是任何一个或多个团队。

我的对象来自实体框架。我将此添加到Staff对象:

public int[] SelectedTeamMembers
{
    get; set;
} 

我现在可以在我的视图中绑定到此属性,用户可以编辑多选列表。在回发编辑表格时,我必须这样做(为了清楚起见添加了评论):

//user.TeamMembers not bound, so get existing memberships
IEnumerable<TeamMember> existingTeamMembers = rep.TeamMembers_Get().Where(t => t.UserId == user.UserID);

//if array is empty, remove all team memberships & avoid null checks in else
if(user.SelectedTeamMembers == null)
{
    foreach(TeamMember tm in existingTeamMembers)
    {
        rep.TeamMembers_Remove(tm);
    }
}
else
{
    // if team members have been deleted, delete them
    foreach (TeamMember tm in existingTeamMembers)
    {
        if (!user.SelectedTeamMembers.Contains(tm.TeamId))
        {
            rep.TeamMembers_Remove(tm);
        }
    }

    // if there are new team memberships, add them
    foreach (int i in user.SelectedTeamMembers)
    {
        if (!existingTeamMembers.Select(t => t.TeamId).Contains(i))
        {
            TeamMember tm = new TeamMember { TeamId = i, UserId = user.UserID };
            rep.TeamMembers_Change(tm);
        }
    }
}

当然,我可以通过将每一部分分解成一个功能来整理这一点,但它仍然感觉像是一个大锤来破解坚果。

是否有更简洁的方法来实现这一目标?

2 个答案:

答案 0 :(得分:2)

作为简化此代码的第一步,您应该评估将forforeach循环组合到一个循环中的可能性。

此外,您知道如何使用LINQ(由初始Where()语句证明),因此使用LINQ及其一些辅助扩展来简化null条件操作:

//user.TeamMembers not bound, so get existing memberships
IEnumerable<TeamMember> existingTeamMembers = rep.TeamMembers_Get().Where(t => t.UserId == user.UserID);

//if array is empty, remove all team memberships & avoid null checks in else
if(user.SelectedTeamMembers == null)
{
    existingTeamMembers.ToList().ForEach(tm => rep.TeamMembers_Remove(tm));
}
else
{
    // if team members have been deleted, delete them
    existingTeamMembers.Where(tm => !user.SelectedTeamMembers.Contains(tm.TeamId)).ToList().ForEach(tm => rep.TeamMembers_Remove(tm));

    // if there are new team memberships, add them    
    user.SelectedTeamMembers.Except(existingTeamMembers.Select(t=> t.TeamId)).ToList().ForEach(i =>
    {
        TeamMember tm = new TeamMember { TeamId = i, UserId = user.UserID };
        rep.TeamMembers_Change(tm);
    });

}

虽然这并未降低条件复杂性(因为所有条件仍然存在),但语法更具可读性。

答案 1 :(得分:0)

你可以这样做......它依赖于使用RemoveRange方法。

实体 - 我将自己用于演示目的

public class User
{

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid Id { get; set; }
    public String Name { get; set; }

}

<强>动作

public ActionResult Action(Guid[] selectedTeamMembers)
{



    using (var ctx = new DatabaseContext())
    {

        //
        // Start by targeting all users!
        //
        var usersToRemove = ctx.Users.AsQueryable();

        //
        // if we have specified a selection then select the inverse.
        //
        if (selectedTeamMembers != null)
        {
            usersToRemove = usersToRemove.Where(x => !selectedTeamMembers.Contains(x.Id));
        }


        //
        // Use the Set Generic as this gives us access to the Remove Range method
        //
        ctx.Set<User>().RemoveRange(usersToRemove);


        ctx.SaveChanges();

    }



    return View();
}

希望这有帮助。