在LINQ中,要執行插入操作,首先需要創建一個與數據庫表對應的類,然后創建一個該類的實例,并將數據添加到實例中。接下來,使用LINQ to SQL的SubmitChanges()
方法將數據插入到數據庫中。以下是一個簡單的示例:
Employee
的數據庫表,其結構如下:CREATE TABLE Employee (
Id INT PRIMARY KEY,
Name NVARCHAR(50),
Age INT,
Department NVARCHAR(50)
);
Employee
表對應的類:public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Department { get; set; }
}
EmployeeDataContext
類,用于連接到數據庫: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()
{
// 創建一個連接字符串
string connectionString = "your_connection_string_here";
// 創建一個EmployeeDataContext實例
EmployeeDataContext context = new EmployeeDataContext(connectionString);
// 創建一個Employee實例并添加數據
Employee employee = new Employee
{
Id = 1,
Name = "John Doe",
Age = 30,
Department = "IT"
};
// 將數據添加到Employees表中
context.Employees.InsertOnSubmit(employee);
// 提交更改
context.SubmitChanges();
Console.WriteLine("Employee inserted successfully!");
}
}
請注意,你需要將your_connection_string_here
替換為實際的數據庫連接字符串。執行上述代碼后,名為"John Doe"的員工將被插入到Employee
表中。