欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

.net core2.0入门使用EF

程序员文章站 2024-01-04 13:25:40
...
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了

上一篇:

下一篇: