ASP.NET 5 EntityFramework.Core 7.0.0-rc1-final问题 - 编译器要求引用7.0.0.0,但找不到该版本

10

我遇到了相同的问题。我已经在我的project.json文件中添加了以下依赖项:

"dependencies": {
    "EntityFramework": "7.0.0-beta4",
    "EntityFramework.Core": "7.0.0-rc1-final",
    "EntityFramework.SqlServer": "7.0.0-beta8",
    "EntityFramework.Commands": "7.0.0-rc1-final"
  },
  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel",
    "ef": "EntityFramework.Commands"
  },
...

我使用了dnu install EntityFrameworkdnu install EntityFramework.SqlServer来安装这些包。 安装程序会在dependencies节点下自动写入"EntityFramework": "7.0.0-beta4"

问题1:让我惊讶的是,当我拉取EntityFramework的智能感知时,我看到的可用版本仅为6.1.3

问题2:当我使用dnu build编译我的应用程序时(手动将EntityFramework程序集(.Core.Commands)添加到dependencies节点后运行了dnu restore命令),我得到了一堆编译错误:

The type 'DbContextOptionsBuilder' is defined in an assembly that is not referenced. You must add a reference to assembly 'EntityFramework.Core, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null'.
D:\Projects\aspnet\apiservice\Models\SampleData.cs(12,41): DNXCore,Version=v5.0 error CS0308: The non-generic method 'IServiceProvider.GetService(Type)' cannot be used with type arguments
D:\Projects\aspnet\apiservice\Models\SampleData.cs(13,32): DNXCore,Version=v5.0 error CS0308: The non-generic method 'IServiceProvider.GetService(Type)' cannot be used with type arguments
D:\Projects\aspnet\apiservice\Models\SampleData.cs(14,29): DNXCore,Version=v5.0 error CS1061: 'object' does not contain a definition for 'Books' and no extension method 'Books' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
D:\Projects\aspnet\apiservice\Models\SampleData.cs(15,42): DNXCore,Version=v5.0 error CS1061: 'object' does not contain a definition for 'Authors' and no extension method 'Authors' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
D:\Projects\aspnet\apiservice\Models\SampleData.cs(17,43): DNXCore,Version=v5.0 error CS1061: 'object' does not contain a definition for 'Authors' and no extension method 'Authors' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
D:\Projects\aspnet\apiservice\Models\SampleData.cs(19,45): DNXCore,Version=v5.0 error CS1061: 'object' does not contain a definition for 'Authors' and no extension method 'Authors' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
D:\Projects\aspnet\apiservice\Models\SampleData.cs(22,29): DNXCore,Version=v5.0 error CS1061: 'object' does not contain a definition for 'Books' and no extension method 'Books' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
D:\Projects\aspnet\apiservice\Models\SampleData.cs(61,29): DNXCore,Version=v5.0 error CS1061: 'object' does not contain a definition for 'SaveChanges' and no extension method 'SaveChanges' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

如果我删除.Core.Commands程序集引用,则项目将能够成功构建。

然后,根据错误信息,我更改了EntityFramework.Core的版本为7.0.0.0

The type 'DbContextOptionsBuilder' is defined in an assembly that is not referenced. You must add a reference to assembly 'EntityFramework.Core, Version=7.0.0.0, Culture=neutral, PublicKeyToken=null'.

但是现在dnu restore给了我以下结果:

Unable to locate Dependency EntityFramework.Core >= 7.0.0
Writing lock file D:\Projects\aspnet\apiservice\project.lock.json
Restore complete, 6675ms elapsed

Errors in D:\Projects\aspnet\apiservice\project.json
    Unable to locate Dependency EntityFramework.Core >= 7.0.0

我是一个asp.net 5 Visual Studio Code平台的新手。由于团队中其他成员使用OSX操作系统,我无法使用Visual Studio 2015

这对我来说是一个学习项目,要求非常简单。连接SQL Server数据库,并使用Entity Framework获取主-从关系数据。

出了点问题!求救!!

先谢谢了

更新

  1. 我可以看到所有版本为7.0.0-rc1-final的包在project.json中有重大更改。我使用Yeoman生成器工具创建了项目,但似乎您通过Visual Studio进行了包的更正。那么,我需要手动更新包版本并还原它们吗?

  2. 当使用Yeoman创建/生成项目时,默认情况下没有添加global.json文件。我可以手动添加这个文件并手动放置代码吗?这样会有效果吗?

  3. 我还可以看到一些额外的包引用被添加到project.json文件中,这些包不是Yeoman生成器自动添加的 - 比如Microsoft.AspNet.Tooling.RazorMicrosoft.Extensions.Logging.ConsoleMicrosoft.Extensions.Logging.DebugMicrosoft.Extensions.Logging等。它们在项目中有效吗?因为生成器没有自动添加它们,所以我可以手动添加它们并使用dnu restore进行还原吗?如果我手动添加它们,会对项目产生影响吗?


请不要在代码无法运行时使用代码片段。 - Gert Arnold
1个回答

14

您应该从依赖项中 删除 "EntityFramework" (删除这行代码 "EntityFramework": "7.0.0-beta4"),并使用

"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
"EntityFramework.MicrosoftSqlServer.Design": "7.0.0-rc1-final",
"EntityFramework.Commands": "7.0.0-rc1-final"

如果你已经添加了"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",那么由于以下依赖关系,你无需显式添加"EntityFramework.Core": "7.0.0-rc1-final"

"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final":
    "EntityFramework.Relational": "7.0.0-rc1-final":
        "EntityFramework.Core": "7.0.0-rc1-final"

我的意思是EntityFramework.MicrosoftSqlServer需要EntityFramework.Relational,而EntityFramework.Relational则需要EntityFramework.Core

你还需要验证一下global.json中是否包含"sdk": { "version": "1.0.0-rc1-update1" }

更新:我检查了你上传的测试项目,发现有很多小问题,我对它进行了修改。你可以在这里下载修改后的项目。不要忘记修复appsettings.json中使用的ConnectionString,其中包含我使用的Server

最重要的更改是使用更简单的BookContext.cs文件:

using Microsoft.Data.Entity;

namespace apiservice.Models {
    public class BookContext : DbContext {
        public DbSet<Author> Authors { get; set; }
        public DbSet<Book> Books { get; set; }
    }
}

以下是SampleData.cs的用法。

using System;
using System.Linq;
using Microsoft.Data.Entity;
using Microsoft.Extensions.DependencyInjection;

namespace apiservice.Models
{
    public static class SampleData
    {
        public static void Initialize(IServiceProvider serviceProvider) {
            var context=serviceProvider.GetService<BookContext>();
            context.Database.Migrate();
            if (!context.Books.Any()) {
                var austen = context.Authors.Add(
                    new Author { LastName = "Austen", FirstName = "Jane" }).Entity;
                var dickens = context.Authors.Add(
                    new Author { LastName = "Dickens", FirstName = "Charles" }).Entity;
                var cervantes = context.Authors.Add(
                    new Author { LastName = "Cervantes", FirstName = "Miguel" }).Entity;

                context.Books.AddRange(
                    new Book {
                        Title = "Pride and Prejudice",
                        Year = 1813,
                        Author = austen,
                        Price = 9.99M,
                        Genre = "Comedy of manners"
                    },
                    new Book {
                        Title = "Northanger Abbey",
                        Year = 1817,
                        Author = austen,
                        Price = 12.95M,
                        Genre = "Gothic parody"
                    },
                    new Book {
                        Title = "David Copperfield",
                        Year = 1850,
                        Author = dickens,
                        Price = 15,
                        Genre = "Bildungsroman"
                    },
                    new Book {
                        Title = "Don Quixote",
                        Year = 1617,
                        Author = cervantes,
                        Price = 8.95M,
                        Genre = "Picaresque"
                    }
                );

                context.SaveChanges(); 
            }
        }
    }    
}

使用以下的dependencies部分来配置project.json文件:

{
  "dependencies": {
    "Microsoft.AspNet.Diagnostics": "1.0.0-rc1-final",
    "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
    "Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
    "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-rc1-final",
    "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final",
    "Microsoft.AspNet.StaticFiles": "1.0.0-rc1-final",
    "Microsoft.AspNet.Tooling.Razor": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.FileProviderExtensions": "1.0.0-rc1-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc1-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc1-final",
    "Microsoft.Extensions.DependencyInjection": "1.0.0-rc1-final",
    "Microsoft.Extensions.CodeGenerators.Mvc": "1.0.0-rc1-final",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-rc1-final",
    "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final",
    "EntityFramework.MicrosoftSqlServer.Design": "7.0.0-rc1-final",
    "EntityFramework.Commands": "7.0.0-rc1-final",
    "System.Net.Http": "4.0.1-beta-23516",
    "Microsoft.Net.Http": "2.2.29",
    "Newtonsoft.Json": "8.0.1"
  },
  "commands": {
    "web": "Microsoft.AspNet.Server.Kestrel",
    "ef": "EntityFramework.Commands"
  },
  "frameworks": {
    "dnx451": { },
    "dnxcore50": { }
  }
}

appsettings.json修复

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    },
    "Data": {
        "DefaultConnection":{
            "ConnectionString": "Server=localhost;Database=BookStore;User Id=sa; Password=******;Trusted_Connection=true;"
        }
    }
  }
}
to
{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Verbose",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Data": {
    "DefaultConnection": {
      "ConnectionString": "Server=localhost;Database=BookStore;User Id=sa; Password=******;Trusted_Connection=true;"
    }
  }
}

(Data不应该在 Logging 下面)

以下是Startup.cs的使用方法

using apiservice.Models;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Data.Entity;


namespace apiservice
{
    public class Startup
    {
        public static IConfigurationRoot Configuration {get; set;}

        public Startup(IHostingEnvironment env)
        {
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<BookContext>(options => 
                    options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"])
                );

            services.AddMvc();
        }

        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            // we need to execute the following two commands before

            //    dnu restore
            //    dnx ef migrations add Initial
            //    dnx ef database update   

            // For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
            try
            {
                using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
                    .CreateScope())
                {
                    serviceScope.ServiceProvider.GetService<BookContext>()
                         .Database.Migrate();
                }
            }
            catch { }

            app.UseIISPlatformHandler();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            SampleData.Initialize(app.ApplicationServices);
        }

        // Entry point for the application.
        public static void Main(string[] args) => WebApplication.Run<Startup>(args);
    }
}

我在Configure方法的注释中写道,应该执行这些命令。

dnx ef migrations add Initial
dnx ef database update

所有包被还原后,dnx ef migrations add Initial 将在项目中创建额外的 Migrations 文件夹,其中包含 20160101205609_Initial.csBookContextModelSnapshot.cs 等文件。 appsettings.json 中定义的数据库将由 dnx ef database update 创建,并在程序运行期间使用 SampleData.cs 填充测试数据。

顺便提一下,我把 package.json 移到了包文件夹中(与 project.json 同级)。你可以不用它们,但是此举可以在 Visual Studio 中更好地管理 npm 包。


我忘了问,我在我的项目树中找不到global.json文件。这是我使用VS Code和Yeoman生成器生成的Web API。 - Subrata Sarkar
谢谢!我正在准备这个项目。 - Subrata Sarkar
@NiladriSarkar:不客气!我手动添加了一些依赖项。其中像Microsoft.Extensions.DependencyInjection这样的依赖项对于我使用的Startup.cs代码非常重要。抱歉,但我自己不使用Yeoman,但即使是Visual Studio 2015 Update 1使用的生成器也不能正常工作。例如,我发现你的演示看起来非常接近教程,但是docs.asp.net上的文本缺少许多内容,并且“Web应用程序”的当前模板没有添加所有依赖项。 - Oleg
2
@NiladriSarkar:换句话说,可以说:ASP.NET 5还没有最终版本,有许多小问题。当然可以在项目目录的父目录中创建global.json和可选的NuGet.config(不仅限于%APPDATA%\NuGet\NuGet.config)。我建议你看一下这个视频,对你可能会有帮助。总的来说,现在支持project.json并不简单。我们可以希望未来会更简单一些。 - Oleg
@Oleg,感谢您提供的示例代码,我已经下载了它。 这里可能需要告诉大家的是,在使用dnx之前,需要先在cmd中运行“dnvm upgrade”。 - Dudi
显示剩余9条评论

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