.net core2.0入门使用EF

Install-Package Microsoft.EntityFrameworkCore.SqlServer
  • 创建model
    public class User
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
  • appsettings加入ConnetionString

  

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "SqlServer": "Data Source=.;Initial Catalog=WebDemo;User Id=sa;Password=******;"
  }
}

  

  • Startup.cs启动文件给 Context 注入ConnetionString
public void ConfigureServices(IServiceCollection services)
        {
            var connetion = Configuration.GetConnectionString("SqlServer");
            services.AddDbContext<WebDemoContext>(options=>options.UseSqlServer(connetion), ServiceLifetime.Singleton,ServiceLifetime.Singleton);
            services.AddMvc();
        }

  

  • 自定义上下文对象
    public class WebDemoContext : DbContext
    {
        public WebDemoContext(DbContextOptions<WebDemoContext> options):base(options)
        {

        }
        public DbSet<User> User { get; set; }
     
    }

  对数据库进行迁移后,接下来就可以使用 WebDemoContext 对 User 进行CRUD了

posted @ 2018-05-08 14:00  站在走廊弹吉他  阅读(248)  评论(0编辑  收藏  举报