با سلام.
با فرض اینکه یک پایگاه داده به نام JoinTest روی سرور وجود دارد؛ کد زیر یک جدول به نام costomer با دو فیلد id و name و یک جدول به نام facter با دو فیدل id و costomerId روی آن ایجاد می کند. در اولین query نام costomerی که مربوط به facterشماره 1 است گرفته و نمایش داده می شود و در ادامه یک view برای نمایش شماره فاکتور و نام مشتری مربوطه ساخته می شود:
//in the name of god
//اللهم صل علی محمد و آل محمد
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
SqlConnection connection =new SqlConnection(@"server=.\sqlexpress;integrated security=true;database=jointest;");
SqlCommand Command = new SqlCommand("", connection);
connection.Open();
Action<string> execute =(string sql) => { Command.CommandText = sql; Command.ExecuteNonQuery(); };
execute("if(exists(select name from sys.tables where name='costomer')) drop table costomer;");
execute("if(exists(select name from sys.tables where name='factor')) drop table factor;");
execute("create table costomer(id int identity,name nvarchar(50))");
execute( "create table factor (id int identity,costomerID int)");
execute("insert into costomer values('costomer1')");
execute( "insert into factor values (1)");
execute("insert into costomer values('costomer2')");
execute("insert into factor values(2)");
Command.CommandText = "select cost.name from dbo.costomer cost join dbo.factor fact on cost.id=fact.costomerID where fact.id=1";
SqlDataReader reader = Command.ExecuteReader();
reader.Read();
MessageBox.Show(reader[0].ToString());
reader.Close();
execute("if(exists(select name from sys.views where name='view1')) drop view view1;");
execute("create view view1 as select cost.name, fact.id FactorId from costomer cost join factor fact on cost.id=fact.costomerID");
Command.CommandText=("select * from view1");
dataGridView1.DataSource =new DataTable();
(dataGridView1.DataSource as DataTable).Load(Command.ExecuteReader());
connection.Close();
}
}
}
اگر همین پایگاه داده را با دو جدول گفته شده به صورت entity model داشته باشیم و بخواهیم costomer مربوط به factor شماره یک را بگیریم به این صورت عمل می کنیم:
JoinTestEntities dbo = new JoinTestEntities();
string costomerName = (from cost in dbo.costomers join fact in dbo.factors on cost.id equals fact.costomerID where fact.id == 1 select cost.name).First();
MessageBox.Show(costomerName);