4

I'm Working with LINQ TO SQL in C# to connect to SQL Database

and I have a table on DataBase called Person which holds information about persons and have the following fields Person_Id, First_Name,Last_Name,Email,Password

I have the following query which returns one row if there is matched :

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

my question is how to convert the query to an instance of Equivalent class which define is :

class Person
{
    public int person_id;
    public string First_Name;
    public string Last_Name;
    public string E_mail;
    public string Password;
    public Person() { }
} 
1
  • how about var person = query.FirstOrDefault()? Commented Jul 15, 2013 at 8:58

2 Answers 2

7

Like this:

Person query = (from a in data.Persons
            where a.Email == "Any Email String"
            select new Person { person_Id = a.Id, and so on }).FirstOrDefault();
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for you,but I want to initialize it to a Person Type not a var and use this reference as return value for a function, how to do that ??
In my answer var will be Person (var is just a keyword to make compiler discover type by itself). You can change var to Person explicitly and it will work just fine (see my edit)
2

I will do it something like :

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.