在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
表中。