c#mysql添加数据示例
时间: 2023-12-30 07:24:07 浏览: 31
以下是使用EntityFramework连接MySQL数据库并添加数据的示例:
```csharp
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
namespace EFCoreDemo
{
public class Program
{
public static void Main(string[] args)
{
using (var context = new MyDbContext())
{
// 创建一个新的实体对象
var newEmployee = new Employee
{
FirstName = "John",
LastName = "Doe",
Department = "IT"
};
// 将实体对象添加到上下文中
context.Employees.Add(newEmployee);
// 保存更改到数据库
context.SaveChanges();
Console.WriteLine("数据添加成功!");
}
}
}
// 定义实体类
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Department { get; set; }
}
// 定义数据库上下文类
public class MyDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// 配置MySQL数据库连接字符串
optionsBuilder.UseMySQL("server=localhost;database=mydatabase;user=root;password=123456");
}
}
}
```
请注意,上述示例中的数据库连接字符串需要根据实际情况进行修改,确保连接到正确的MySQL数据库。