使用LINQ TO SQL将查询转换为对象

时间:2013-07-15 08:51:03

标签: c# linq-to-sql

我正在使用C#中的LINQ TO SQL连接到SQL数据库

我在DataBase上有一个名为Person的表格,其中包含有关人员的信息,并包含以下字段Person_IdFirst_NameLast_NameEmailPassword

我有以下查询,如果匹配,则返回一行:

LINQDataContext data = new LINQDataContext();
            var query = from a in data.Persons
                        where a.Email == "Any Email String"
                        select a;

我的问题是如何将query转换为定义为的等效类的实例:

class Person
{
    public int person_id;
    public string First_Name;
    public string Last_Name;
    public string E_mail;
    public string Password;
    public Person() { }
} 

2 个答案:

答案 0 :(得分:7)

像这样:

Person query = (from a in data.Persons
            where a.Email == "Any Email String"
            select new Person { person_Id = a.Id, and so on }).FirstOrDefault();

答案 1 :(得分:2)

我会这样做:

var query = (from a in data.Persons
            where a.Email == "Unique Email String"
            select new Person { person_Id = a.Id, etc etc });

//By using this code, you can add more conditions on query as well..

//Now the database hit will be made
var person = query.FirstOrDefault();