.Net Core 使用EF Core Code First创建数据库,同时使用命令创建数据库
数据访问层添加nuget引用 Microsoft.EntityFrameworkCore.SqlServer
1.appsetting.json 增加数据库连接
{ "ConnectionStrings": { "DefaultConnection": "User ID=sa;Password=123@abcd;Initial Catalog=zmBlog;Data Source=USER-20170918PP\\SQLEXPRESS" }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Warning" } } }
2.Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //数据库初始化数据 InitializeNetCoreBBSDatabase(app.ApplicationServices); }
private void InitializeNetCoreBBSDatabase(IServiceProvider serviceProvider) { using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope()) { var db = serviceScope.ServiceProvider.GetService<DataContext>(); if (db.Database != null && db.Database.EnsureCreated()) { db.Power_User.AddRange(CreateUserList()); db.SaveChanges(); } } } public List<Power_User> CreateUserList() { List<Power_User> list = new List<Power_User>(); list.Add(new Power_User() { Id= Guid.NewGuid(),UID="abc"}); return list; }
DataContext.cs
public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { } public DbSet<Power_User> Power_User { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //modelBuilder.Entity<Power_User>().ToTable("Power_User"); } }
Repository.cs
public class Repository<T> : IRepository<T> where T : BaseEntity { private readonly DataContext _dbContext; public Repository(DataContext dbContext) { _dbContext = dbContext; } public virtual T GetById(int id) { return _dbContext.Set<T>().Find(id); } public virtual IEnumerable<T> List() { return _dbContext.Set<T>().AsEnumerable(); } public virtual IEnumerable<T> List(System.Linq.Expressions.Expression<Func<T, bool>> predicate) { return _dbContext.Set<T>() .Where(predicate) .AsEnumerable(); } public void Add(T entity) { _dbContext.Set<T>().Add(entity); _dbContext.SaveChanges(); } public void Edit(T entity) { _dbContext.Entry(entity).State = EntityState.Modified; _dbContext.SaveChanges(); } public void Delete(T entity) { _dbContext.Set<T>().Remove(entity); _dbContext.SaveChanges(); } }
IRepository.cs
public interface IRepository<T> where T : BaseEntity { T GetById(int id); IEnumerable<T> List(); IEnumerable<T> List(Expression<Func<T, bool>> predicate); void Add(T entity); void Delete(T entity); void Edit(T entity); }
数据迁移
程序根目录cmd命令
dotnet ef migrations add InitialCreate //提交到数据库 dotnet ef database update
Nuget包管理控制台命令
Add-Migration zmblog
Update-Database zmblog
浙公网安备 33010602011771号