.net core连接数据库

一、新建项目

首先新建一个web应用程序,如图所示


选择web应用程序(模型视图控制器)并选择确定


二、连接数据库

在appsettings.json中添加以下代码

  "ConnectionStrings": {
    "DefaultConnection": "Server=.;Database=MyData;Trusted_Connection=True;MultipleActiveResultSets=true"
  },

在Models文件夹下创建实体类和DbContext类


DbContext类内容如下所示

public class OADbContext : DbContext
    {
        public OADbContext(DbContextOptions options)
            : base(options)
        {
        }

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

将Startup类里面的ConfigureServices替换成下列代码

public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<OADbContext>(options =>
                               options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc();
        }




猜你喜欢

转载自blog.csdn.net/zhouxueli32/article/details/80508797
今日推荐