How to convert a simple DLINQ Query to a data set object

    技术2022-05-11  11

    In this article I will represent a trick of how to convert a given DLINQ query to a data set object in order to make use of it as a data source for several controls such as grid view, data grid view and so forth. As the Query object couldn't be directly used unless in very particular cases with particular controls. So I invite you to follow this walkthrough:During this tutorial the NorthWind SQL Server data base is used as a data source. In order to download it you can reach it via this link Create a new windows project and name it LinqQueyToDataSet2. Add a reference to the System.Data.Linq3. Add a data grid view into the Form1 and set its Dock property to fill4. Add a reference to the System.Data.Linq.Mappinq that enables us to define Entity classes witches are a sort of proxies' objects that represent the effective tables located in the NorthWind data base5. Add this entity class within the scope of the form1 class      [Table(Name="Employees" )]              class Employee              {                  [Column(Name = "EmployeeID", IsPrimaryKey = true)]                  public int Identifier;                  [Column(Name = "LastName" )]                  public string LastName;                  [Column(Name = "FirstName" )]                  public string FirstName;                  [Column(Name = "Title")]                  public string Title;                  [Column(Name = "BirthDate")]                  public string BirthDate;                  [Column(Name = "Address" )]                  public string Address;                  [Column(Name = "City")]                  public string City;                  [Column(Name = "Country" )]                  public string Country;              }6. Establish the connection to the NorthWind data base by defining a DataContext object as bellow7. Implement the load event handler of the Form1 as follow:8. Run the application nowThat's it.

    DataContext oNorthWind = new DataContext(@"Data Source=STANDARD;Initial Catalog=" + @"C:/SQL SERVER 2000 SAMPLE DATABASES/NORTHWND.MDF';" + "Integrated Security=True");


    private void Form1_Load(object sender, EventArgs e) { /* This is a simple DLinq Query that selects all rows from the employee data table */ var Query = from emp in oNorthWind.GetTable() select emp; /*This command will get all inforamtion from the Query. The transformation will be done thanks to the GetCommand of the data context object*/ SqlCommand oCommand = oNorthWind.GetCommand(Query) as SqlCommand; //The data adapter will be used to fill data SqlDataAdapter oAdapter = new SqlDataAdapter(); //The rest is known.... oAdapter.SelectCommand = oCommand; DataSet oDataSet = new DataSet(); oAdapter.Fill(oDataSet); dataGridView1.DataSource = oDataSet; dataGridView1.DataMember = oDataSet.Tables[0].TableName; }