1条回答
- weixin_44875637 2019-04-04 17:11关注
一.新建一个.net core的MVC项目
新建好项目后,不能像以前一样直接在新建项中添加ef, 需要用命令在添加ef的依赖
二.EF Core实体框架核心安装:
工具> NuGet软件包管理器>软件包管理器控制台
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Tools
Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design
安装成功后就可以在Nuget依赖项中看到
四.更具一个命令就可以从数据库生成model了
方式一:(通过现有数据库创建模型)
Scaffold-DbContext "Server=.;Database=Food;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
该命令会在Models文件夹下生成数据库中的表和上下文对象
注:执行这一步的时候出现了点问题 ,因为系统是win7,powershell版本太低了,不支持这个命令,需要安装 3.0以上的powershell版本才行 添加成功后在models可以看到, 生成了上下文对象与和表对应的model 现在就可以使用EF了
复制代码
public IActionResult Index()
{FoodContext fc = new FoodContext(); List<ProType> ptlist = fc.ProType.ToList(); ViewBag.ptlist = ptlist; return View(); }
复制代码
方式二:(通过模型创建数据库)1.创建上下文类
复制代码
public class FoodContext : DbContext
{
public FoodContext (DbContextOptions options)
: base(options)
{ }public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }public List< Post > Posts { get; set; }
}public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }public int BlogId { get; set; }
public Blog Blog { get; set; }
}
复制代码
2.在startup.cs的ConfigureServices方法中中将上下文类注册为全局服务:
services.AddDbContext(options => options.UseSqlServer(connection));3.在appsetting文件中增加连接字符串connection
4.创建数据库
工具 - > NuGet软件包管理器 - >软件包管理器控制台
//创建模型的初始表
Add-Migration InitialCreate
//将新迁移应用于数据库
Update-Database五.使用依赖注入来装载EF的上下文对象
.net core中用了不少的依赖注入,官方文档中也推荐使用 1:删除方法
复制代码
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer(@"Server=.;Database=Food;Trusted_Connection=True;");
}
复制代码
2:添加方法public FoodContext(DbContextOptions<FoodContext> options) : base(options) { }
添加的是一个构造函数用于注入
3:在startup.cs的configureServices方法中添加依赖注入
复制代码
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();services.AddDbContext<FoodContext>(option => { option.UseSqlServer("Data Source =.; Initial Catalog = EFCore_dbfirst; User ID = sa; Password = sa.123"); }); }
复制代码
解决 无用评论 打赏 举报
悬赏问题
- ¥20 易康econgnition精度验证
- ¥15 线程问题判断多次进入
- ¥15 msix packaging tool打包问题
- ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
- ¥15 python的qt5界面
- ¥15 无线电能传输系统MATLAB仿真问题
- ¥50 如何用脚本实现输入法的热键设置
- ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
- ¥30 深度学习,前后端连接
- ¥15 孟德尔随机化结果不一致