Reputation: 4394
I am trying to get the first item in the database that has the a given 'UserGuid', but the 'First' extension method is throwing the following exception: System.InvalidOperationException: Sequence contains no elements
Here are some examples of what works and what does not:
// Works
var FoundUser1 = MyEntities.Users.First();
// Works
var FoundUser3 = MyEntities.Users.ToList().First(r => r.UserGuid == SampleUserGuid);
// Throws System.InvalidOperationException: Sequence contains no elements.
var FoundUser2 = MyEntities.Users.First(r => r.UserGuid == SampleUserGuid);
Anyone have any ideas?
EDIT
More weird code examples:
// UserList1 is empty
var Query1 = from x in MyEntities.Users
where x.UserGuid == criteria.Value
select x;
var UserList1 = Query1.ToList();
// UserList2 has 3 users, including one with a
// matching guid value.
var Query2 = from x in MyEntities.Users
select x;
var UserList2 = Query2.ToList();
var Query22 = from x in Query2
where x.UserGuid == criteria.Value
select x;
var UserList22 = Query22.ToList();
// Works
User FoundUser = null;
foreach (var ThisUser in MyEntities.Users)
{
if (ThisUser.UserGuid == criteria.Value)
FoundUser = ThisUser;
}
Upvotes: 1
Views: 895
Reputation: 4394
It turns out the issue was with SQLite's handing of GUID types. If you set
BinaryGuids=True
then they are saved as 16 byte binaries and cannot be 'matched' against string based guids. You can also set that to be false and they match as strings, but you need to watch the case for the alpha chars.
Upvotes: 0
Reputation: 180858
Try comparing their string values, as in
x.UserGuid.ToString() == criteria.Value.ToString()
There are other examples on the internet of people who have trouble comparing guids directly. Here is one:http://bytes.com/groups/net-vb/364009-comparing-guids
Upvotes: 0
Reputation: 180858
In this piece of code:
// UserList1 is empty
var Query1 = from x in mgr.ObjectContext.Users
where x.UserGuid == criteria.Value
select x;
var UserList1 = Query1.ToList();
What is the value of criteria.Value, if you Debug.Print it?
Upvotes: 0
Reputation: 180858
What is the exception, is it an "Empty Set" exception or something similar?
Try
FirstOrDefault()
Instead of
First()
and see what happens. First() will throw an exception if there are no records available. FirstOrDefault() will give you am empty User object if no records are available.
Upvotes: 4