NET6 使用EF简单示例

  1. 环境
    1. 开发平台:NET6
    2. 数据库:MSSQLLocalDB
    3. 开发工具:VS2022
    4. 操作系统:Windows11
    5. ORM:Entity FrameworkCore
  2. 创建一个ASP.NET Core Web 应用项目 EFDemo
  3. 添加数据库链接语句,在appsettings.json文件中添加ConnectionStringsDefaultStringappsettings.json文件内容如下:
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
    "AllowedHosts": "*",
    "ConnectionStrings": {
        "DefaultString": "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=Persion;Integrated Security=True;Connect Timeout=30;Encrypt=False;Trust Server Certificate=False;Application Intent=ReadWrite;Multi Subnet Failover=False"
    }
}

4. 添加EntityFrameworkCroe的NuGet包如下:
        4.1、Microsoft.EntityFrameworkCore Version="6.0.27"
        4.2、Microsoft.EntityFrameworkCore.Design Version="6.0.27"
        4.3、Microsoft.EntityFrameworkCore.SqlServer Version="6.0.27"
        4.4、Microsoft.EntityFrameworkCore.Tools Version="6.0.27"

5.选择“视图->其他窗口->程序包管理器控制台”,查看EntityFramework帮助输入命令如下:
      Get-Help about_EntityFrameworkCore
 

6.在项目中添加文件夹“Models”、“Data”
        6.1、“Models”文件夹中添加Persion类,代码如下:

  public class Persion
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Age { get; set; }
    }

        6.2、 “Data”文件夹中添加DataContext类,代码如下:

using EFDemo.Models;
using Microsoft.EntityFrameworkCore;

namespace EFDemo.Data
{
    public class DataContext:DbContext
    {
        public DataContext(DbContextOptions options) : base(options)
        {

        }

        //DbSet属性
        public DbSet<Persion> Persions { get; set; }
    }
}

        6.3、向Program.cs文件中添加代码,

builder.Services.AddDbContext<DataContext>(options =>
{
    //链接MSSQL
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultString"));
    
});

         6.4、builder.Services.AddDbContext<DataContext>();
                  Program.cs文件代码如下:

using EFDemo.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<DataContext>(options =>
{
    //链接MSSQL
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultString"));
    
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

        6.5、在程序包管理器控制台中输入Add-Migration InitPersion,项目目录中自动生成了Migrations文件夹,文件夹中包含两个迁移文件。注意此时没有生成数据库
在程序包管理器控制台中输入Update-Database -Verbose,-Verbose用于显示详细的生成数据库的过程。此时在“视图->SQL Server对象资源管理器”中查看生成的数据库。
到这里Entity Framework的迁移操作已经完成,接下来我们来操作一下数据接口。
向项目添加MVC功能, 在Program.cs文件中添加语句。
添加语句如下:

//添加MVC
builder.Services.AddMvc(options =>
{
    options.EnableEndpointRouting = false;
});

//使用MVC
app.UseMvc(routes =>
{
    routes.MapRoute("Default", "{Controller}/{Action}/{id?}");
});

        6.6、Program.cs文件代码如下:

 

using EFDemo.Data;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
//添加MVC
builder.Services.AddMvc(options =>
{
    options.EnableEndpointRouting = false;
});

builder.Services.AddDbContext<DataContext>(options =>
{
    //链接MSSQL
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultString"));
    
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();
//使用MVC
app.UseMvc(routes =>
{
    routes.MapRoute("Default", "{Controller}/{Action}/{id?}");
});

app.Run();

        6.7、项目中添加Controllers文件夹,添加控制器HomeController。控制器中代码如下:

using EFDemo.Data;
using EFDemo.Models;
using Microsoft.AspNetCore.Mvc;
using System;

namespace EFDemo.Controllers
{
    [Route("Home")]
    public class HomeController : Controller
    {
        private readonly DataContext _dataContext;
        public HomeController(DataContext dataContext)
        {
            _dataContext = dataContext;
        }
        [Route("Create")]
        [HttpGet]
        public IActionResult Create()
        {
            Persion _persion1 = new Persion() {  Age = "18", Name = "Persion1" };
            Persion _persion2 = new Persion() {  Age = "18", Name = "Persion2" };
            Persion _persion3 = new Persion() {  Age = "18", Name = "Persion3" };
            Persion _persion4 = new Persion() {  Age = "18", Name = "Persion4" };
            Persion _persion5 = new Persion() {  Age = "18", Name = "Persion5" };

            _dataContext.Persions.Add(_persion1);
            _dataContext.Persions.Add(_persion2);
            _dataContext.Persions.Add(_persion3);
            _dataContext.Persions.Add(_persion4);
            _dataContext.Persions.Add(_persion5);
            _dataContext.SaveChanges();
            return Ok("数据创建成功");
        }

        [Route("Get")]
        [HttpGet]
        public IActionResult Get(int? id)
        {
            object _object = _dataContext.Persions.Find(id);
            return Ok(_object);
        }
    }
}

        6.8、运行起项目后,在浏览器分别输入,其中7260是端口号,每台机器的端口号可能是不一样的:
                6.8.1、https://localhost:7260/Home/Create
                6.8.2、https://localhost:7260/Home/Get/?id=3

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
C# Winform应用程序中使用Entity Framework (EF) 可以通过以下步骤实现: 1. 创建一个C# Winform应用程序项目。 2. 在项目中添加对Entity Framework的引用。可以通过NuGet包管理器安装Entity Framework。 3. 创建一个数据模型类,用于映射数据库表。可以使用EF的Code First或者DB First方法来创建模型类。 4. 配置数据库连接字符串。可以在应用程序的配置文件中添加连接字符串,或者在代码中直接指定连接字符串。 5. 使用EF的DbContext类来操作数据库。可以通过DbContext类的实例来执行查询、插入、更新和删除等操作。 下面是一个简单示例代码,演示了如何在C# Winform应用程序中使用EF进行数据库操作: ```csharp using System; using System.Linq; using System.Windows.Forms; namespace WinformEFExample { public partial class MainForm : Form { private MyDbContext dbContext; public MainForm() { InitializeComponent(); dbContext = new MyDbContext(); } private void MainForm_Load(object sender, EventArgs e) { // 查询数据 var customers = dbContext.Customers.ToList(); dataGridView1.DataSource = customers; } private void btnAdd_Click(object sender, EventArgs e) { // 添加数据 var customer = new Customer { Name = txtName.Text, Email = txtEmail.Text }; dbContext.Customers.Add(customer); dbContext.SaveChanges(); // 刷新数据 var customers = dbContext.Customers.ToList(); dataGridView1.DataSource = customers; } } } ``` 请注意,上述示例中的`MyDbContext`和`Customer`是根据具体的数据模型和数据库表来定义的,你需要根据自己的实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

为风而战

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值