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