.NET Core Entity使用Entity Framework Core链接数据库

本文详细介绍使用Entity Framework Core (EF Core)与SQL Server数据库进行交互的方法。包括安装必需的Nuget包、配置数据连接字符串、创建实体模型、定义数据库上下文及通过两种不同方式实现数据访问的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先安装Nuget包

Install-package Microsoft.EntityFrameworkCore
Install-package Microsoft.EntityFrameworkCore.SqlServer

Micorsoft.EntityFrameworkCore:EF框架的核心包
Micorsoft.EntityFrameworkCore.SqlServer:针对SqlServer数据库的扩展

其次设置(appsettings.json)配置文件的数据连接字符串

"ConnectionStrings": {
    "SqlServer": "Data Source=localhost;Initial Catalog=testingdb;Integrated Security=False;Persist Security Info=False;User ID=sa;Password=password"
  }

创建实体(province)

namespace MicroCore
{
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    [Table("dt_province")]
    public class province
    {
        [Key]
        /// <summary>
        /// 自动
        /// </summary>
        public int id { set; get; }
        /// <summary>
        /// 当前标识
        /// </summary>
        public string code { set; get; }
        /// <summary>
        /// 名称
        /// </summary>
        public string name { set; get; }
    }
}

    

方法一、通过配置链接数据库

1、创建Entity Framework Core配置

namespace MicroCore
{
    using Microsoft.EntityFrameworkCore;
    public class EFContext : DbContext
    {
        public EFContext(DbContextOptions<EFContext> options) : base(options)
        {

        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<province>(entity =>
            {
                entity.ToTable("dt_province");
                entity.HasKey(a => a.id);
            });
        }
        public DbSet<province> province { get; set; }
    }
}

2、Startup 启动注册链接

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddApplicationInsightsTelemetry(Configuration);
    services.AddEntityFrameworkSqlServer().AddDbContext<EFContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServer")));
}

3、Index.cshtml.cs调用数据

namespace MicroCore.Pages
{
    public class IndexModel : PageModel
    {
        private readonly EFContext db;
        public IndexModel(EFContext db)
        {
            this.db = db;
        }

        public void OnGet()
        {
            var result = db.province.Where(p => p.id == 1).ToList();
        }
    }
}

  

方法二、自定义配置链接数据库

1、创建Entity Framework Core配置

namespace MicroCore
{
    using Microsoft.EntityFrameworkCore;
    public class EFContext : DbContext
    {
        public static string ConnectionString { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {            
            optionsBuilder.UseSqlServer(ConnectionString, b => b.UseRowNumberForPaging());
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<province>(entity =>
            {
                entity.ToTable("dt_province");
                entity.HasKey(a => a.id);
            });
        }
        public DbSet<province> province { get; set; }
    }
}

2、Startup 取得配置链接

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    EFContext.ConnectionString = Configuration.GetConnectionString("SqlServer");
}

3、Index.cshtml.cs调用数据

namespace MicroCore.Pages
{
    public class IndexModel : PageModel
    {
        public void OnGet()
        {
            EFContext db = new EFContext();         
            var result = db.province.Where(p => p.id == 3).ToList();
        }
    }
}

  

  本文源码下载    

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值