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

首先安装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();
}
}
}

  

  本文源码下载    

  

上一篇:与大家分享学习微信小程序开发的一些心得


下一篇:Dev GridControl数据导出格式问题