依赖项引用
![](https://img.haomeiwen.com/i2305452/b4ce38f1b4961984.png)
public class CoreNetContext:DbContext
{
public CoreNetContext()
{
}
public DbSet<tUser> TUsers { get; set; }
public CoreNetContext(DbContextOptions option) : base(option)
{
}
}
在appsettings.json中添加数据库连接字符串
"ConnectionStrings": {
"CoreNet5Context": "Data Source=数据库服务器;Initial Catalog=数据库名称;Persist Security Info=True;User ID=账号;Password=密码"
},
在Startup.cs中添加数据库连接字符串
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSession();
//数据库连接字符串配置
services.AddDbContext<CoreNetContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("CoreNet5Context")));
}
添加一个用户的数据
public class tUser:EntityBase
{
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Company { get; set; }
[Column("Price",TypeName = "MONEY")]
public decimal Price { get; set; }
}
public class EntityBase
{
//主键递增(默认是主键递增)
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
}
用命令根据model生成数据库,程序包管理控制台以此输入以下命令。
Add-Migration addUser
Update-Database
网友评论