EF6通过model生成数据库并使用LINQ进行操作
2023年7月13日发(作者:)
EF6通过model⽣成数据库并使⽤LINQ进⾏操作安包依赖包:ef core(core版本的ef)ef sqlserver(数据库,也可使⽤其他数据库⽐如ef mysql等)ef tool(数据迁移⼯具)书写DbContext创建DbContextpublic class AppDbContext : DbContext{ public AppDbContext(DbContextOptions options) : base(options) { }
// 表,有多少个数据模型就有多少张表,就得添加多少个DbSet public DbSet Persons { get; set; }}创建数据模型public class Person{ [Column(TypeName = "uniqueIdentifier")] // 表⽰这个是唯⼀的 public Guid PKUser { get; set; }
[Key] public int UserID { get; set; } public string UserName { get; set; }}向应⽤注⼊上下⽂修改,public void ConfigureServices(IServiceCollection services){ ontext(options => { Server(connectionString); });}若不想⼿动写connectionString也可以查看sqlserver视图中添加的数据库属性中的连接属性。通过⽂件配置⽅式设置数据库连接修改,加⼊如下内容// 只要是个键值对的字符串就⾏,能取到就OK"DbContext": { "Server": "connectionString"}修改刚刚的ate readonly IConfiguration Configuration; // 依赖于ef tool包public Startup(IConfiguration configuration) // 注⼊依赖,⾯向接⼝编程{ uration = configuration;}public void ConfigureServices(IServiceCollection services){ ontext(options => { // DbContext => Server,":"相当于"."操作符,取值 Server(uration["DbContext:Server"]); });}创建数据库打开程序包管理控制台,输⼊add-migration ,完成数据迁移,这个时候会⽣成⼀个数据迁移的cs⽂件,内容为创建表,然后再运⾏update-database,完成数据库中Persons表的创建。命令⾏⽅式为dotnet ef migrations add Migrations,这个迁移命令需要全局安装ef-tool命令,具体可搜索。dotnet ef database update,完成数据库的创建或更新
发布者:admin,转转请注明出处:http://www.yc00.com/news/1689248201a225689.html
评论列表(0条)