-3

I am trying to use this method to return a boolean value based on whether or not the custody already exists in the database.

var custody = db.Custodies.LastOrDefault(c => c.studentId == id);
if (db.Custodies.Contains(custody) && custody.custodyEndTime == null)
{
    return true;
}
    return false;
}

The Custodies table uses a composite primary key but I only want to search by studentId, so I can't use Find(). I want to find the custody entry based on the studentId to check if that student is currently in a custody with no custodyEndTime.

I tried using a linq query but that gave me an anonymous type and it complained about that too.

Any help would be great.

Cheers.

Schming
  • 51
  • 7

3 Answers3

3

You can use Any to determine whether any element in the collection satisfies given condition or not:

bool exists = db.Custodies.Any(c => c.studentId == id && c.custodyEndTime == null)
Alex
  • 1,433
  • 9
  • 18
0

Try this. any() will give you true value if any record found with studentid else return false

return db.Custodies.Where(c => c.studentId == id && c.custodyEndTime == null).Any();
jignesh patel
  • 964
  • 7
  • 13
0

You could use the Any method for this.

bool custodyExists = db.Custodies.Any(c => c.studentId == id && c.custodyEndTime == null);

Have a look at MSDN for more information.

For more LINQ samples have a look at 101 LINQ-Samples. Most of them are working with LING to SQL very well.

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51