Reputation: 15
I am currently trying to select multiple columns in C# with Linq-to-SQL. When looking at other threads just as this one it is a pretty simple thing to do, so I tried:
var users = context.GetTable<DbHelper.User>();
var query = from u in users
where u.Email == TbUsername.Text
select new { u.Active, u.Password };
if(!query.Any())
{
MessageBox.Show("Could not find an account with that Email");
return;
}
var result = query.First(); // Error occurs here
User table in DbHelper
:
[Table(Name="Users")]
public class User
{
[Column(IsPrimaryKey = true, AutoSync = AutoSync.OnInsert, IsDbGenerated = true)]
public int Id { get; set; }
[Column]
public int RoleID { get; set; }
[Column]
public string Email { get; set; }
[Column]
public string Password { get; set; }
[Column]
public string Firstname { get; set; }
[Column]
public string Lastname { get; set; }
[Column]
public int OfficeID { get; set; }
[Column]
public string Birthdate { get; set; }
[Column]
public int Active { get; set; }
}
The table looks like this in SQL Server:
[ID] INT IDENTITY (1, 1) NOT NULL,
[RoleID] INT NOT NULL,
[Email] NVARCHAR(150) NOT NULL,
[Password] NVARCHAR(50) NOT NULL,
[FirstName] NVARCHAR(50) NULL,
[LastName] NVARCHAR(50) NOT NULL,
[OfficeID] INT NULL,
[Birthdate] DATE NULL,
[Active] BIT NULL,
Which results in an error
System.InvalidCastException: The conversion is invalid
What is wrong with my code? It's really confusing since it seems to work for others. If you need more code please let me know
Upvotes: 0
Views: 218
Reputation: 39348
As the type of the Active column in your database table is 'bit', EF expects a property of type 'bool'. 0==false, 1==true, as you might expect.
Upvotes: 1
Reputation: 755471
Try to use .FirstOrDefault()
:
var result = query.FirstOrDefault();
If the result
is null after this call, then your selection just didn't return any rows from the database table.
Upvotes: 1