10

I am having the same issue. I have added the following dependencies in my project.json file:

"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"
  },
...

I used dnu install EntityFramework and dnu install EntityFramework.SqlServer to install the packages. "EntityFramework": "7.0.0-beta4", was written under dependencies node automatically by the installer itself.

Issue / Question 1: To my surprise when I was pulling in the intellisence for EntityFramework the available version I am presenting with is only 6.1.3!

Issue 2: When I am compiling my application using dnu build (I ran dnu restore command after adding EntityFramework assemblies (.Core and .Commands) manually under dependencies node I am getting a bunch of compilation errors:

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?)

If I remove .Core and .Commands assembly references the project build fine.

Then I changed the version for EntityFramework.Core to 7.0.0.0 as mentioned in the error:

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'.

But dnu restore now gave me the following:

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

I am a newbie in asp.net 5 Visual Studio code platform. And I cannot use Visual Studio 2015 as other members of the dev team are using OSX.

This is a learning project for me. Requirement is pretty straight forward. Connect a SQL Server database, pull master-child relational data using Entity Framework.

Screwed up! Help!!

Thanks in advance

UPDATE

  1. I can see the major changes in project.json for all packages with version 7.0.0-rc1-final. I used Yeoman generator tool to create the project but looks like you corrected the package through Visual Studio. So, do I have to update the package version manually and restore them?

  2. When the project was created/generated by Yeoman, there was no global.json file added by default. Can I add this manually and put the code inside by hand? Will this work?

  3. I can also see some additional package references are added to project.json file which were not added by default by Yeoman generator - like Microsoft.AspNet.Tooling.Razor, Microsoft.Extensions.Logging.Console, Microsoft.Extensions.Logging.Debug, Microsoft.Extensions.Logging etc. Are they all being used effectively in the project? Because the generator did not add them automatically, again, can I add them manually and restore using dnu restore? Will this have any impact on the project if I add them manually?

Subrata Sarkar
  • 2,975
  • 6
  • 45
  • 85

1 Answers1

14

You should remove "EntityFramework" from dependencies (remove the line "EntityFramework": "7.0.0-beta4") and use

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

only. You don't need to add "EntityFramework.Core": "7.0.0-rc1-final" explicitly if you added "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final" because of the following dependencies:

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

I mean that EntityFramework.MicrosoftSqlServer requires EntityFramework.Relational, which requires EntityFramework.Core.

You should verify additionally that global.json contains "sdk": { "version": "1.0.0-rc1-update1" }.

UPDATED: I examined the test project which you uploaded. It had many small problems. I modified it. You can download the modified project here. Don't forget to fix the ConnectionString used in appsettings.json, it contains the Server which I used at me.

The most important changes are the usage of more simple 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; }
    }
}

the usage of the following 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(); 
            }
        }
    }    
}

the usage of project.json with the following dependencies part:

{
  "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": { }
  }
}

fixing of appsettings.json from

{
  "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 should not be under Logging)

and the usage of the following 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);
    }
}

I wrote in the comment inside of Configure method that one should execute the commands

dnx ef migrations add Initial
dnx ef database update

after all packages are restored. dnx ef migrations add Initial will create additional Migrations folder in the project with the files like 20160101205609_Initial.cs and BookContextModelSnapshot.cs. The database defined in appsettings.json will be created by dnx ef database update and it will be filled with test data from SampleData.cs during forking with the program.

By the way I moved package.json inside of the package folder (on the same level as project.json). You use the packages not, but the movement makes the npm packages visible and management in Visual Studio.

Oleg
  • 220,925
  • 34
  • 403
  • 798
  • If I have understood correctly I now have this: `"EntityFramework.Relational": "7.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"` Compilation errors coming up are: `...The non-generic method 'IServiceProvider.GetService(Type)' cannot be used with type arguments...The non-generic method 'IServiceProvider.GetService(Type)' cannot be used with type arguments` – Subrata Sarkar Jan 01 '16 at 14:29
  • I forgot to ask, I cannot find a global.json in my project tree. It's a Web API I am developing with VS Code and the project generated using Yeoman generator. – Subrata Sarkar Jan 01 '16 at 14:34
  • @NiladriSarkar: Could you include **full `project.json`** which you use currently. It would be mostly simple if you upload somewhere your test project and I could compile it on my computer. What I mean in my answer, that you **don't need** to include `EntityFramework.Core` and `EntityFramework.Relational` if you included `"EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final"` - the dependencies of `EntityFramework.MicrosoftSqlServer` will be loaded automatically. – Oleg Jan 01 '16 at 14:37
  • May I send the project to you through email or something? I don't have a server yet where I can upload! Meanwhile I removed .Core and .Relational references. However, still getting `'IServiceProvider.GetService(Type)' cannot be used with type arguments` error when compiling. – Subrata Sarkar Jan 01 '16 at 14:41
  • @NiladriSarkar: You can send me to oleg.kiriljuk@ok-soft-gmbh.com. I use Visual Studio 2015 Update 1, but in general command line tool should work too. The typical structure of the project should be: the main folder of the solution with `global.json` and optional `NuGet.Config` file (see [here](https://docs.nuget.org/consume/nuget-config-file)). Then you have `src` subfolder which contains the folder for every project in your solution. Every project contains `project.json`. – Oleg Jan 01 '16 at 14:44
  • Thank you! I am preparing the project. – Subrata Sarkar Jan 01 '16 at 14:51
  • Hi, I sent you a zip via wetransfer.com. Please download from http://we.tl/ibgivBpskU. Thank you for your help. – Subrata Sarkar Jan 01 '16 at 15:29
  • @NiladriSarkar: I wrote **UPDATED** part to my answer. You can download modified project from [here](http://www.ok-soft-gmbh.com/ForStackOverflow/Test_Project.zip) – Oleg Jan 01 '16 at 23:44
  • Thanks a ton! Everything works now. However, I put some questions under UPDATE section of my original question. If you please enlighten me on those that would be extremely helpful for me :) – Subrata Sarkar Jan 02 '16 at 05:31
  • @NiladriSarkar: You are welcome! I added some dependencies manually. Some from there like `Microsoft.Extensions.DependencyInjection` are really very important for the code `Startup.cs`, which I use. Sorry, but I don't use `Yeoman` myself, but even the generators used by Visual Studio 2015 Update 1 works not correctly. For example I found that your demo looks very close to [the tutorial](https://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html), but the text on docs.asp.net miss many things and the current template of "Web Application" don't add all dependencies. – Oleg Jan 02 '16 at 10:08
  • @NiladriSarkar: [The tutorial](https://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html) don't contains important steps with creating of `BookContext.cs` (`ApplicationDbContext.cs`), the step [Add scaffolding](https://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html#add-scaffolding) don't work at all because one didn't had any "Add scaffolding" and "MVC 6 Controller with views, using Entity Framework". After reading [the issue](https://github.com/aspnet/Tooling/issues/290#issuecomment-158465907) I added `Microsoft.Extensions.CodeGenerators.Mvc` and other. – Oleg Jan 02 '16 at 10:14
  • 2
    @NiladriSarkar: In other words, one can say: ASP.NET 5 is still not final and one have many small problems. One can of cause create `global.json` and optionally `NuGet.config` in the parent directory of the project directory (not only `%APPDATA%\NuGet\NuGet.config`). I would recommend you to look [the video](https://channel9.msdn.com/Blogs/DevRadio/DR1619) which could be helpful for you. In general it's really not simple to support `project.json` now. We can hope that it will be more simple in the future. – Oleg Jan 02 '16 at 10:22
  • Thanks for the gentle push I needed on a "similar" project (don't think it's the same, but it's damn close) – WernerCD May 12 '16 at 01:00
  • @Oleg, Tnx 4 your example code, I downloaded it. The only thing maybe people here will have to know is to run first: "dnvm upgrade" from the cmd in order to be able to use dnx. – Dudi Aug 04 '16 at 23:48