score:9
This is probably because you didn't override the equality comparisons (Equals
, GetHashCode
, operator==
) on your Role
class. Therefore, it was doing reference comparison, which really isn't the best idea, as if they're not the same object, it makes it think it's a different. You need to override those equality operators to provide value equality.
score:1
It will be your equality comparison for a Role.
The object in commentUserRole
is not the same object as the one you are looking for commentUser.Roles
.
Your context object will create a new object when you select from it and populate your Roles property with a collection of new Roles. If your context is not tracking the objects in order to return the same object when a second copy is requested then it will be a different object even though all the properties may be the same. Hence the failure of Contains
Your Any
clause is explicitly checking the Name property which is why it works
Try making Role implement IEquatable<Role>
public class Role : IEquatable<Role> {
public bool Equals(Role compare) {
return compare != null && this.Name == compare.Name;
}
}
Whilst MSDN shows you only need this for a List<T>
you may actually need to override Equals
and GetHashCode
to make this work
in which case:
public class Role : IEquatable<Role> {
public bool Equals(Role compare) {
return compare != null && this.Name == compare.Name;
}
public override bool Equals(object compare) {
return this.Equals(compare as Role); // this will call the above equals method
}
public override int GetHashCode() {
return this.Name == null ? 0 : this.Name.GetHashCode();
}
}
score:1
When using the Contains
-method, you check if the the array Roles
of the user-object contains the object you have retrieved from the database beforehand. Though the array contains an object for the role "admin" it does not contain the exact object you fetched before.
When using the Any
-method you check if there is any role having the name "admin" - and that delivers the expected result.
To get the same result with the Contains
-method implement the IEquatable<Role>
-interface on the role-class and compare the name to check whether two instances have actually the same value.
score:4
You have to override Equals
(and always also GetHashCode
then) if you want to use Contains
. Otherwise Equals
will just compare references.
So for example:
public class Role
{
public string RoleName{ get; set; }
public int RoleID{ get; set; }
// ...
public override bool Equals(object obj)
{
Role r2 = obj as Role;
if (r2 == null) return false;
return RoleID == r2.RoleID;
}
public override int GetHashCode()
{
return RoleID;
}
public override string ToString()
{
return RoleName;
}
}
Another option is to implement a custom IEqualityComparer<Role>
for the overload of Enumerable.Contains
:
public class RoleComparer : IEqualityComparer<Role>
{
public bool Equals(Role x, Role y)
{
return x.RoleID.Equals(y.RoleID);
}
public int GetHashCode(Role obj)
{
return obj.RoleID;
}
}
Use it in this way:
var comparer = new RoleComparer();
User commentUser = userRepository.GetUserById(comment.userId);
Role commentUserRole = context.Roles.Single(x=>x.Name == "admin");
if(commentUser.Roles.Contains(commentUserRole, comparer))
{
// ...
}
Source: stackoverflow.com
Related Articles
- LINQ Source Code Available
- Determine if LINQ Enumerable contains object based on a condition?
- creating Linq to sqlite dbml from DbLinq source code
- LINQ entity data model generated code error - The type 'DBContexts.Category' already contains a definition for 'ID'
- The source contains no DataRows using Linq
- source code for LINQ 101 samples
- Is there a way I can do a foreach that contains code in a LINQ expression?
- Linq to sql code for contains
- c# Linq or code to extract groups from a single list of source data
- Convert string[] to int[] in one line of code using LINQ
- Code equivalent to the 'let' keyword in chained LINQ extension method calls
- LINQ Contains Case Insensitive
- linq where list contains any in list
- Determine if a sequence contains all elements of another sequence using Linq
- Linq code to select one item
- Error: "The specified LINQ expression contains references to queries that are associated with different contexts"
- How are people unit testing code that uses Linq to SQL
- Linq query list contains a list
- Sequence contains no elements exception in linq without even using Single
- The source contains no DataRows
- Linq filter List<string> where it contains a string value from another List<string>
- Determine sequence contains no element using LINQ
- Check if a string within a list contains a specific string with Linq
- LINQ To SQL exception: Local sequence cannot be used in LINQ to SQL implementation of query operators except the Contains operator
- How to use Linq to check if a list of strings contains any string in a list
- LINQ : exception as " Sequence contains no elements"
- LINQ query to perform a projection, skipping or wrapping exceptions where source throws on IEnumerable.GetNext()
- Using Linq to do a Contains with multiple values
- LINQ - array property contains element from another array
- Linq - How to select items from a list that contains only items of another list?
- Using LINQ to pull MembershipUser.Username into a new object
- how to write linq to sql with lambda for this sql query
- Lambda expression in IF condition
- IEnumerable extension methods (System.Linq) unavailable when inheriting from collection and implementing enumerable interfaces
- List of object - combining condition check within the list with local variables outside of it
- Child Objects Filter In EF
- Async method in query syntax
- linq-to-xml syntax error: retrieve attribute value
- C# LINQ - Recognize unique index violation
- Improving The Performance Of My Application?
- Linq orderby culture (danish, æøå)
- Left Outer Join LINQ To Entities
- Linq remove multiple objects
- linq to entity,How does the where clause use ?: Expression
- Linq query performance with new object in `Where`
- Linq2db entity framework update query for dynamic table and column
- Tally Values of Each Column
- LINQ - joining two tables and getting the values from the right part of the join if it exists throw exception
- How to avoid nothing with Linq Query?
- Cannot use list of classes by base interface