获取其属性在枚举中不存在的对象

时间:2018-06-22 13:46:50

标签: c# linq ienumerable

多个答案使我想到了以下两种解决方案,但它们似乎都无法正常工作。

我有2个对象

public class DatabaseAssignment : AuditableEntity
{
    public Guid Id { get; set; }
    public string User_Id { get; set; }
    public Guid Database_Id { get; set; }       
}

public class Database : AuditableEntity
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string Server { get; set; }
    public bool IsActive { get; set; }
    public Guid DatabaseClientId { get; set; }
}

现在,前端将返回给定用户的所有选定数据库对象(作为IEnumerable)。我从给定用户的数据库中获取所有当前的DatabaseAssignments,并通过Database.ID属性将它们与数据库进行比较。我的目标是找到可以从数据库中删除的DatabaseAssignments。但是,我的解决方案不断返回所有要删除的DatabaseAssignments。

if (databases != null)
{
    var unitOfWork = new UnitOfWork(_context);
    var userDatabaseAssignments = unitOfWork.DatabaseAssignments.GetAll().Where(d => d.User_Id == user.Id);

    //var assignmentsToRemove = userDatabaseAssignments.Where(ud => databases.Any(d => d.Id != ud.Database_Id));
    var assignmentsToRemove = userDatabaseAssignments.Select(ud => userDatabaseAssignments.FirstOrDefault()).Where(d1 => databases.All(d2 => d2.Id != d1.Database_Id));
    var assignmentsToAdd = databases.Select(d => new DatabaseAssignment { User_Id = user.Id, Database_Id = d.Id }).Where(ar => assignmentsToRemove.All(a => a.Database_Id != ar.Database_Id));

    if (assignmentsToRemove.Any())
    {   
       unitOfWork.DatabaseAssignments.RemoveRange(assignmentsToRemove);
    }
    if (assignmentsToAdd.Any())
    {
       unitOfWork.DatabaseAssignments.AddRange(assignmentsToAdd);
    }
    unitOfWork.SaveChanges();
}

1 个答案:

答案 0 :(得分:1)

我认为您正在寻找Except扩展名,请查看此链接

LINQ: Select where object does not contain items from list

或其他包含方法,请参见下面的Fiddler链接:

https://dotnetfiddle.net/lKyI2F