netcore EF基于数据模型创建数据库

在.Net Core中,使用EntityFramework Core来基于数据模型创建数据库。EntityFrameworkCore是一个轻量级、跨平台的ORM(对象关系映射)框架,提供了很多功能来简化数据库操作和管理

示例

  1. 安装EntityFrameWork Core
nuget Microsoft.EntityFrameWorkCore
  1. 定义数据模型 
 1  public class Product
 2     {
 3         public int Id { get; set; }
 4 
 5         public string Name { get; set; }
 6 
 7         public decimal Price { get; set; }
 8 
 9         public string Description { get; set; }
10 
11         public DateTime CreateTime { get; set; }
12 
13         public DateTime UpdateTime { get; set; }
14     }
15  

 

 public DbSet<Product> Products { get; set; }

        public MyDbContext(DbContextOptions<MyDbContext> context) : base(context)
        {

        }
    }

 

 

builder.Services.AddDbContext<MyDbContext>(opt =>
{
    opt.UseSqlServer(builder.Configuration.GetConnectionString("Default"));
});

appsetting.json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "Default": "Data Source=.;Initial Catalog=Demo;Integrated Security=True;Trust Server Certificate=true"
  }
}

 

//需要加上Trust Server Certificate=true 否则报错SSL Provider
A connection was successfully established with the server, but then an error occurred during the login process. (provider: SSL Provider, error: 0 - 

 


需要nuget Microsoft.EntityFrameworkCore.Tools
add-Migration initCreation
update-database

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2023-07-18 10:21  小溪_1  阅读(26)  评论(0编辑  收藏  举报