UseSqlServer方法在MVC 6中缺失。

39

我正在尝试在MVC 6中实现Entity Framework 7,在这个页面这里说要这样做

services.AddEntityFramework()
    .AddSqlServer()
    .AddDbContext<MusicStoreContext>(options =>
                        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));

但是对我来说,UseSqlServer 方法不可见?有人知道如何使它可见吗?还是这是配置实体框架的一种旧方法?

我的 startup.cs 文件看起来像这样

using FluentValidation;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;

namespace me.namespace.project
{
    public class Startup
    {
        public static IConfiguration Configuration { get; set; }

        public Startup(IHostingEnvironment env)
        {
            // Setup configuration sources.
            Configuration = new Configuration()
                .AddJsonFile("config.json")
                .AddEnvironmentVariables();
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // entity framework
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<DataContext>();

        }
    }
}
5个回答

48

安装 Microsoft.EntityFrameworkCore.SqlServer 1.0.1 包对我有用 Microsoft.EntityFrameworkCore 的版本为 1.1.0


3
截至2017年3月24日,这是正确的答案。NuGet包为:Microsoft.EntityFrameworkCore.SqlServer - Win
1
安装包 Microsoft.EntityFrameworkCore.SqlServer,完美运行。 - Linda Lawton - DaImTo

40

UseSqlServer 是在命名空间 Microsoft.Data.Entity 中的扩展方法,因此您需要在代码中导入它,就像这样:

using Microsoft.EntityFrameworkCore;

谢谢,这正是我所需要的。 - Gillardo
正常运行了...现在出现另一个问题,提示“未配置数据库提供程序。通过在您的 DbContext 类中重写 OnConfiguring 方法或在设置服务时在 AddDbContext 方法中进行配置来配置数据库提供程序。”我不知道为什么,因为我的 startup.cs 文件已经声明了连接字符串? - Gillardo
听起来很容易解决,但这是另一个问题 :) - DavidG
不是问题 - 需要 @Win 的另一个答案中的评论。 - CodeHxr

28
自发布此文后,程序集已更名。作为 EntityFrameworkCore 的一部分,您现在需要添加以下 using 语句。
using Microsoft.EntityFrameworkCore;

然后,您将能够使用.UseSqlServer扩展方法来配置您的上下文。


22

这是一个 NuGet 包问题

安装以下包及其正确版本:

 1.  Microsoft.EntityFrameworkCore(Latest Version)
 2.  Microsoft.EntityFrameworkCore.SqlServer(1.0.4 Version)

截至2022年08月17日,.Net 6的EF Core库仍缺少一个包。我不得不从NuGet下载SqlServer包才能获取.UseSqlServer()扩展。 - Michael Tucker

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接