NoahWillCrow NoahWillCrow - 1 month ago 6
C# Question

"Sequence contains no matching element" on ToList()

I have a piece of code that should retrieve a

List
of
User
objects.

public List<User> GetUsersBySessions(string[] sessionStrs, string ip)
{
if (sessionStrs == null || string.IsNullOrEmpty(ip))
return new List<User>();
using (var ctx = new DataContext())
{
var ret = ctx.Sessions.Include("User").Where(s => sessionStrs.Contains(s.ID) && s.IP.Equals(ip)).Select(s => s.User).ToList();
return ret;
}
}


The arguments
sessionStrs
and
ip
are properly passed into the method. However, I'm getting the following error:

error

How could this type of error be caused when I'm not using any
.First()
or
.Single()
? I'm just trying to get all items in a table that fit into an array return them as a
List
. I've never seen such a problem before.

The following line of code even causes an error:

var ret = ctx.Sessions.ToList();


Here is my
DataContext
:

public class DataContext : DbContext
{
public GenericDataContext()
: base(CONNECTION_STRING) //My CONNECTION_STRING is defined somewhere else, but I'm going to hide that for security's sake.
{
}

public DbSet<Password> Passwords { get; set; }
public DbSet<Session> Sessions { get; set; }
public DbSet<User> Users { get; set; }

}


And here is my
Session
model:

[Table("tbl_Sessions")]
public class Session
{

[Column("SessionID")]
[MaxLength(24)]
[Required]
[Key]
public string ID { get; set; }

[Column("UserID")]
[Required]
public int UserID { get; set; }

[Column("IP")]
[MaxLength(24)]
[Required]
public string IP { get; set; }

[ForeignKey("UserID")]
public virtual User User { get; set; }

}


NOTE
Both
Classes
are properly namespaced and have their proper
using
statements, as well.

Answer

The actual answer to this question had to do with the fact that one of my models had two Keys, each of which was a string. When I changed said model to have an int as it's Key, all worked well.