使用LINQ to SQL将查询转换为对象
本文关键字:转换 对象 查询 LINQ to SQL 使用 | 更新日期: 2023-09-27 18:22:33
我正在C#中使用LINQ TO SQL连接到SQL数据库
我在数据库上有一个名为Person
的表,它保存有关人员的信息,并具有以下字段Person_Id
、First_Name
、Last_Name
、Email
、Password
我有以下查询,如果匹配,它会返回一行:
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() { }
}
像这样:
Person query = (from a in data.Persons
where a.Email == "Any Email String"
select new Person { person_Id = a.Id, and so on }).FirstOrDefault();
我会这样做:
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();