在LINQ中,要執(zhí)行插入操作,首先需要?jiǎng)?chuàng)建一個(gè)與數(shù)據(jù)庫(kù)表對(duì)應(yīng)的類,然后創(chuàng)建一個(gè)該類的實(shí)例,并將數(shù)據(jù)添加到實(shí)例中。接下來,使用LINQ to SQL的SubmitChanges()
方法將數(shù)據(jù)插入到數(shù)據(jù)庫(kù)中。以下是一個(gè)簡(jiǎn)單的示例:
Employee
的數(shù)據(jù)庫(kù)表,其結(jié)構(gòu)如下:CREATE TABLE Employee (
Id INT PRIMARY KEY,
Name NVARCHAR(50),
Age INT,
Department NVARCHAR(50)
);
Employee
表對(duì)應(yīng)的類:public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Department { get; set; }
}
EmployeeDataContext
類,用于連接到數(shù)據(jù)庫(kù):using System.Data.Linq;
public class EmployeeDataContext : DataContext
{
public EmployeeDataContext(string connectionString) : base(connectionString) { }
public Table<Employee> Employees { get { return this.GetTable<Employee>(); } }
}
using System;
class Program
{
static void Main()
{
// 創(chuàng)建一個(gè)連接字符串
string connectionString = "your_connection_string_here";
// 創(chuàng)建一個(gè)EmployeeDataContext實(shí)例
EmployeeDataContext context = new EmployeeDataContext(connectionString);
// 創(chuàng)建一個(gè)Employee實(shí)例并添加數(shù)據(jù)
Employee employee = new Employee
{
Id = 1,
Name = "John Doe",
Age = 30,
Department = "IT"
};
// 將數(shù)據(jù)添加到Employees表中
context.Employees.InsertOnSubmit(employee);
// 提交更改
context.SubmitChanges();
Console.WriteLine("Employee inserted successfully!");
}
}
請(qǐng)注意,你需要將your_connection_string_here
替換為實(shí)際的數(shù)據(jù)庫(kù)連接字符串。執(zhí)行上述代碼后,名為"John Doe"的員工將被插入到Employee
表中。