In this article, I will discuss how we can execute a SQL Query directly from LINQ.ExplanationTo execute a SQL query there is a method in the DataContext class called ExecuteQuery: ExecuteQuery takes two input parameters:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using System.Data.Linq; namespace Relatedtable{ class Program { static DataClasses1DataContext context; static void Main(string[] args) { context = new DataClasses1DataContext(); var result = context.ExecuteQuery<Person>("select * from Person"); foreach (var r in result) { Console.WriteLine(r.PersonID + r.FirstName); } int idToPass = 1; var result1 = context.ExecuteQuery<Person> ("select * from Person where PersonID={0}", idToPass); foreach (var r in result1) { Console.WriteLine(r.PersonID + r.FirstName); } Console.ReadKey(true); var result2 = context.ExecuteQuery<Person> ("select * from Person where PersonID='1'"); foreach (var r in result2) { Console.WriteLine(r.PersonID + r.FirstName); } Console.ReadKey(true); }}}On pressing F5 you should get output as below:
I hope this article was useful. Thanks for reading.
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: