locked
The EF Core tools in error when create the migration RRS feed

  • Question

  • User433211055 posted

    I'm experimenting with a solution of 3 projects:

    • WebApi .net core 2.1 - Test.Api
    • Class Library .net core 2.1 Target Framework - Test.Data
    • Class Library .net core 2.1 Target Framework - Test.Model

    In Test.Data I created a Context Class, DbInizializer Class, Repository, ... In Test.Model I created my Entities

    In Test.Api I want to create the migration and installed this package :

    <Project Sdk="Microsoft.NET.Sdk.Web">
    
      <PropertyGroup>
        <TargetFramework>netcoreapp2.1</TargetFramework>
      </PropertyGroup>
    
      <ItemGroup>
        <Folder Include="wwwroot\images\" />
      </ItemGroup>
    
      <ItemGroup>
        <PackageReference Include="AutoMapper" Version="7.0.1" />
        <PackageReference Include="AutoMapper.Data" Version="2.0.0" />
        <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="5.0.1" />
        <PackageReference Include="FluentValidation" Version="8.0.100" />
        <PackageReference Include="Microsoft.AspNetCore.App" />
        <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.4">
          <PrivateAssets>all</PrivateAssets>
          <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
        </PackageReference>
    
      </ItemGroup>
    
      <ItemGroup>
        <ProjectReference Include="..\Test.Data\Test.Data.csproj" />
        <ProjectReference Include="..\Test.Model\Test.Model.csproj" />
      </ItemGroup>
    
    </Project>

    In Startup.cs add this code

    services.AddDbContext<TestContext>(options =>                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                    b => b.MigrationsAssembly("Test.Api")));

    I create also this class "DesignTimeDbContextFactory"

    public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<TestContext>
        {
            public TestContext CreateDbContext(string[] args)
            {
                IConfigurationRoot configuration = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json")
                    .Build();
    
                var builder = new DbContextOptionsBuilder<TestContext>();
    
                var connectionString = configuration.GetConnectionString("DefaultConnection");
                //configuration["Data:Products:ConnectionString"];
                    //
    
                builder.UseSqlServer(connectionString);
    
                return new TimeShareContext(builder.Options);
            }
        }

    When I run this

    dotnet ef migrations add "InitialCreate" -o "Data\Migrations"

    Obtain this

    The EF Core tools version '2.1.3-rtm-32065' is older than that of the runtime '2.1.4-rtm-31024'. Update the tools for the latest features and bug fixes. Your target project 'Test.Api' doesn't match your migrations assembly 'Test.Data'. Either change your target project or change your migrations assembly.

    Change your migrations assembly by using DbContextOptionsBuilder. E.g. options.UseSqlServer(connection, b => b.MigrationsAssembly("Test.Api")). By default, the migrations assembly is the assembly containing the DbContext. Change your target project to the migrations project by using the Package Manager Console's Default project drop-down list, or by executing "dotnet ef" from the directory containing the migrations project.

    I've done all the package upgrades.

    I don't understand because doesn't work.

    BR

    Wednesday, October 10, 2018 2:17 PM

All replies

  • User-1764593085 posted

    Hi cicciuzzo,

    cicciuzzo

    Your target project 'Test.Api' doesn't match your migrations assembly 'Test.Data'. Either change your target project or change your migrations assembly.

    Based on the error message, have you tried to change MigrationsAssembly , set your default project as Test.Api and then add migrations in PMC?

    services.AddDbContext<TestContext>(options => 
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Test.Data")));

    Here shows similar problem which you could refer to.

    If you still have the error,could you share your project or a demo to us which could reproduce your problem? 

    Xing

    Thursday, October 11, 2018 4:28 AM
  • User433211055 posted

    Hi 

    Thanks for support.. but the migrations doen't works fine..

    Now with this command i create the migration in Test.Api Project, I run this command in Test.Data:

    dotnet ef --startup-project ../Test.Api migrations add "InitialCreate" -o "..\Test.Api\Data\Migrations" -c TestContext

    I change my code in Startup.cs (Test.Api Project) in :

    services.AddDbContext<TestContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
    b => b.MigrationsAssembly("Test.Data")));

    When I Run this in Test.api project

    dotnet ef database update 

    obtain : No migrations were applied. The database is already up to date. Done.

    obviously the data base in empty, it create only the database but without table.

    This is my connection string in appsetting.json

    {
    "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=Test;Trusted_Connection=True;"
    },

    BR

    Thursday, October 11, 2018 9:04 AM
  • User-1764593085 posted

    Hi cizziuzzo,

    Have you add DbSet for you model class in your DbContext like below. Also, you'd better share your project to us if you still have problems.

    public class TradeContext : DbContext
        {
            public TradeContext(DbContextOptions<TradeContext> options) : base(options)
            {
    
            }
          
            public DbSet<Customer> Customers { get; set; }
            public DbSet<Product> Products { get; set; }
    
          
        }
    

    Xing

    Thursday, October 11, 2018 9:28 AM
  • User433211055 posted

    If you still have the error,could you share your project or a demo to us which could reproduce your problem? 

    Link for project

    Thursday, October 11, 2018 9:36 AM
  • User433211055 posted

    My context

    public class TimeShareContext : DbContext
    {
    public DbSet<Schedule> Schedules { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Attendee> Attendees { get; set; }

    public TimeShareContext(DbContextOptions options) : base(options) { }

    ***

    Have you add DbSet for you model class in your DbContext like below. Also, you'd better share your project to us if you still have problems.

    My Project

    Thursday, October 11, 2018 11:44 AM
  • User-1764593085 posted

    Hi cicciuzzo,

    After trying many times, I make it by taking following actions:

    1.Remove your DesignTimeDbContextFactory.cs file

    2. Change Startup.cs like below:

    services.AddDbContext<TimeShareContext>(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                    b => b.MigrationsAssembly(typeof(Startup).Assembly.FullName)));

    3.Set both your startup project and Default project in PMC as TimeShaer.Api 

    4.In PMC

    Add-migration Test1 -o "Data/Migrations"
    
    Update-database

    Or use below command under TimeShare.Api

    dotnet ef migrations add Test -o "Data/Migrations"
    
    dotnet ef database update

    You could refer to my project based on what you gave here.

    Xing

    Friday, October 12, 2018 9:24 AM
  • User-2054057000 posted

    First of all build your solution and see if you have been getting any errors. EF Core Migrations will not work if you have some unsolved errors. 

    Moreover you have 3 projects in your solution. 

    • WebApi .net core 2.1 - Test.Api
    • Class Library .net core 2.1 Target Framework - Test.Data
    • Class Library .net core 2.1 Target Framework - Test.Model

    You have to make one project as startup project and reference the other 2 project assemblies in the startup project. 

    Moreover I think you are just starting with EF Core so why don't you create just one project and do all your EF core migrations stuff from there itself.  

    See the Migrations in Entity Framework Core tutorial here.

    Friday, October 12, 2018 11:27 AM
  • User433211055 posted

    You could refer to my project based on what you gave here.

    Xing

    Thank for support, now work...

    What does not work is

    context = (TimeShareContext)serviceProvider.GetService(typeof(TimeShareContext));

    InitializeSchedules();

    Obtain this when run service.

    InvalidOperationException: Cannot resolve scoped service 'TimeShare.Data.TimeShareContext' from root provider.

    Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)

    Friday, October 12, 2018 12:20 PM
  • User-2054057000 posted

    InvalidOperationException: Cannot resolve scoped service

    Its is problem of Dependency Injection. You need to see your startup.cs class configservices() method and find if the DI scope is defined or not. Refer to this MS DI tutorial on ASP.NET CORE.

    Friday, October 12, 2018 3:32 PM
  • User-1764593085 posted

    Hi cicciuzzo,

    So you could add migration successfully but initialize the data failed.  Try below steps to seed the database.

    1.Remove TimeShareDbInizializer.Initialize(app.ApplicationServices); in your startup.cs Configure.

    2.Follow this tutorial to seed the database correctly by modifying your TimeShareDbInizializer.cs and Program.cs

    using TimeShare.Model;
    using TimeShare.Model.Entities;
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.EntityFrameworkCore;
    
    namespace TimeShare.Data
    {
        public static class TimeShareDbInizializer
        {
           
            public static void Initialize(IServiceProvider serviceProvider)
            {
                using (var context = new TimeShareContext(
                     serviceProvider.GetRequiredService<DbContextOptions<TimeShareContext>>()))
                {
                   
                    if (!context.Users.Any())
                    {
                        User user_01 = new User { Name = "Chris Sakellarios", Profession = "Developer", Avatar = "avatar_02.png" };
    
                        User user_02 = new User { Name = "Charlene Campbell", Profession = "Web Designer", Avatar = "avatar_03.jpg" };
    
                        User user_03 = new User { Name = "Mattie Lyons", Profession = "Engineer", Avatar = "avatar_05.png" };
    
                        User user_04 = new User { Name = "Kelly Alvarez", Profession = "Network Engineer", Avatar = "avatar_01.png" };
    
                        User user_05 = new User { Name = "Charlie Cox", Profession = "Developer", Avatar = "avatar_03.jpg" };
    
                        User user_06 = new User { Name = "Megan	Fox", Profession = "Hacker", Avatar = "avatar_05.png" };
    
                        context.Users.Add(user_01); context.Users.Add(user_02);
                        context.Users.Add(user_03); context.Users.Add(user_04);
                        context.Users.Add(user_05); context.Users.Add(user_06);
    
                        context.SaveChanges();
                    }
    
                    if (!context.Schedules.Any())
                    {
                        Schedule schedule_01 = new Schedule
                        {
                            Title = "Meeting",
                            Description = "Meeting at work with the boss",
                            Location = "Korai",
                            CreatorId = 1,
                            Status = ScheduleStatus.Valid,
                            Type = ScheduleType.Work,
                            TimeStart = DateTime.Now.AddHours(4),
                            TimeEnd = DateTime.Now.AddHours(6),
                            Attendees = new List<Attendee>
                        {
                            new Attendee() { ScheduleId = 1, UserId = 2 },
                            new Attendee() { ScheduleId = 1, UserId = 3 },
                            new Attendee() { ScheduleId = 1, UserId = 4 }
                        }
                        };
    
                        Schedule schedule_02 = new Schedule
                        {
                            Title = "Coffee",
                            Description = "Coffee with folks",
                            Location = "Athens",
                            CreatorId = 2,
                            Status = ScheduleStatus.Valid,
                            Type = ScheduleType.Coffee,
                            TimeStart = DateTime.Now.AddHours(3),
                            TimeEnd = DateTime.Now.AddHours(6),
                            Attendees = new List<Attendee>
                        {
                            new Attendee() { ScheduleId = 2, UserId = 1 },
                            new Attendee() { ScheduleId = 1, UserId = 3 },
                            new Attendee() { ScheduleId = 2, UserId = 4 }
                        }
                        };
    
                        Schedule schedule_03 = new Schedule
                        {
                            Title = "Shopping day",
                            Description = "Shopping therapy",
                            Location = "Attica",
                            CreatorId = 3,
                            Status = ScheduleStatus.Valid,
                            Type = ScheduleType.Shopping,
                            TimeStart = DateTime.Now.AddHours(3),
                            TimeEnd = DateTime.Now.AddHours(6),
                            Attendees = new List<Attendee>
                        {
                            new Attendee() { ScheduleId = 3, UserId = 1 },
                            new Attendee() { ScheduleId = 3, UserId = 4 },
                            new Attendee() { ScheduleId = 3, UserId = 5 }
                        }
                        };
    
                        Schedule schedule_04 = new Schedule
                        {
                            Title = "Family",
                            Description = "Thanks giving day",
                            Location = "Home",
                            CreatorId = 5,
                            Status = ScheduleStatus.Valid,
                            Type = ScheduleType.Other,
                            TimeStart = DateTime.Now.AddHours(3),
                            TimeEnd = DateTime.Now.AddHours(6),
                            Attendees = new List<Attendee>
                        {
                            new Attendee() { ScheduleId = 4, UserId = 1 },
                            new Attendee() { ScheduleId = 4, UserId = 2 },
                            new Attendee() { ScheduleId = 4, UserId = 5 }
                        }
                        };
    
                        Schedule schedule_05 = new Schedule
                        {
                            Title = "Friends",
                            Description = "Friends giving day",
                            Location = "Home",
                            CreatorId = 5,
                            Status = ScheduleStatus.Cancelled,
                            Type = ScheduleType.Other,
                            TimeStart = DateTime.Now.AddHours(5),
                            TimeEnd = DateTime.Now.AddHours(7),
                            Attendees = new List<Attendee>
                        {
                            new Attendee() { ScheduleId = 4, UserId = 1 },
                            new Attendee() { ScheduleId = 4, UserId = 2 },
                            new Attendee() { ScheduleId = 4, UserId = 3 },
                            new Attendee() { ScheduleId = 4, UserId = 4 },
                            new Attendee() { ScheduleId = 4, UserId = 5 }
                        }
                        };
    
                        Schedule schedule_06 = new Schedule
                        {
                            Title = "Meeting with the boss and collegues",
                            Description = "Discuss project planning",
                            Location = "Office",
                            CreatorId = 3,
                            Status = ScheduleStatus.Cancelled,
                            Type = ScheduleType.Other,
                            TimeStart = DateTime.Now.AddHours(22),
                            TimeEnd = DateTime.Now.AddHours(30),
                            Attendees = new List<Attendee>
                        {
                            new Attendee() { ScheduleId = 4, UserId = 1 },
                            new Attendee() { ScheduleId = 4, UserId = 2 },
                            new Attendee() { ScheduleId = 4, UserId = 5 }
                        }
                        };
    
                        Schedule schedule_07 = new Schedule
                        {
                            Title = "Scenario presentation",
                            Description = "Discuss new movie's scenario",
                            Location = "My special place",
                            CreatorId = 6,
                            Status = ScheduleStatus.Cancelled,
                            Type = ScheduleType.Other,
                            TimeStart = DateTime.Now.AddHours(11),
                            TimeEnd = DateTime.Now.AddHours(13),
                            Attendees = new List<Attendee>
                        {
                            new Attendee() { ScheduleId = 4, UserId = 4 },
                            new Attendee() { ScheduleId = 4, UserId = 2 },
                            new Attendee() { ScheduleId = 4, UserId = 3 }
                        }
                        };
    
                        context.Schedules.Add(schedule_01); context.Schedules.Add(schedule_02);
                        context.Schedules.Add(schedule_03); context.Schedules.Add(schedule_04);
                        context.Schedules.Add(schedule_05); context.Schedules.Add(schedule_06);
                    }
    
                    context.SaveChanges();
                }
            }
        }
    }

    Program.cs:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    using TimeShare.Data;
    
    namespace TimeShare.Api
    {
        public class Program
        {
            public static void Main(string[] args)
            {
                //CreateWebHostBuilder(args).Build().Run();
    
                var host = CreateWebHostBuilder(args).Build();
    
                using (var scope = host.Services.CreateScope())
                {
                    var services = scope.ServiceProvider;
    
                    try
                    {
                        var context = services.GetRequiredService<TimeShareContext>();
                        context.Database.Migrate();
                        TimeShareDbInizializer.Initialize(services);
                    }
                    catch (Exception ex)
                    {
                        var logger = services.GetRequiredService<ILogger<Program>>();
                        logger.LogError(ex, "An error occurred seeding the DB.");
                    }
                }
    
                host.Run();
            }
    
            public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
                WebHost.CreateDefaultBuilder(args)
                    .UseStartup<Startup>();
        }
    }
    

    Xing

    Friday, October 12, 2018 4:25 PM