简体   繁体   English

C#Linq-to-SQL多列

[英]C# Linq-to-SQL multiple columns

I am currently trying to select multiple columns in C# with Linq-to-SQL. 我目前正在尝试使用Linq-to-SQL在C#中选择多个列。 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 : 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: 该表在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 System.InvalidCastException:转换无效

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 如果您需要更多代码,请告诉我

Try to use .FirstOrDefault() : 尝试使用.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. 如果此调用后result为null,则您的选择仅不返回数据库表中的任何行。

As the type of the Active column in your database table is 'bit', EF expects a property of type 'bool'. 由于数据库表中“活动”列的类型为“位”,因此EF期望的属性类型为“布尔”。 0==false, 1==true, as you might expect. 如您所料,0 == false,1 == true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM