Я не понимаю, что не так.
Я попытался сделать простой CRUD в .NET Core MVC с очень простой моделью, которая имеет несколько полей. < /p>
Это мои модели: < /p>
public class Employee
{
[Key] public int EmployeeId { get; set; }
[Required] public string FistName { get; set; }
[Required] public string LastName { get; set; }
public int PositionId { get; set; }
public virtual Position Position { get; set; }
}
public class Position
{
[Key]
public int PositionId { get; set; }
public string PositionName { get; set; }
public ICollection Employees { get; set; }
}
< /code>
Тогда я сделал контекст приложения: < /p>
public class EmployeeContext : DbContext
{
public EmployeeContext(DbContextOptions options)
: base(options)
{
}
public DbSet Employees { get; set; }
public DbSet
Positions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity()
.HasOne(e => e.Position)
.WithMany()
.HasForeignKey(e => e.PositionId);
}
}
< /code>
и зарегистрированный контекст в startup.cs: < /p>
public void ConfigureServices(IServiceCollection services)
{
services.Configure(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext(item =>item.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
< /code>
может потребоваться еще один файл кода .csproj и program.cs < /p>
net461
full
all
runtime; build; native; contentfiles; analyzers; buildtransitive
all
runtime; build; native; contentfiles; analyzers; buildtransitive
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup();
}
< /code>
Затем я попытался сделать сначала мигрировать, но я вижу очень странную ошибку
add -migration FirstInit -verbose < /p>
Using project 'Crud'.
Using startup project 'Crud'.
Build started...
Build succeeded.
C:\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.2\tools\net461\win-x86\ef.exe migrations add FirstInit --json --verbose --no-color --prefix-output --assembly C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe --startup-assembly C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe --project-dir C:\source\repos\Crud\Crud\ --language C# --working-dir C:\source\repos\Crud --root-namespace Crud
Using assembly 'Crud'.
Using startup assembly 'Crud'.
Using application base 'C:\source\repos\Crud\Crud\bin\Debug\net461'.
Using working directory 'C:\source\repos\Crud\Crud'.
Using root namespace 'Crud'.
Using project directory 'C:\source\repos\Crud\Crud\'.
Using configuration file 'C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe.config'.
Using assembly 'Crud'.
Using startup assembly 'Crud'.
Using application base 'C:\source\repos\Crud\Crud\bin\Debug\net461'.
Using working directory 'C:\source\repos\Crud\Crud'.
Using root namespace 'Crud'.
Using project directory 'C:\source\repos\Crud\Crud\'.
Finding DbContext classes...
Finding IDesignTimeDbContextFactory implementations...
Finding application service provider...
Finding Microsoft.Extensions.Hosting service provider...
Using environment 'Development'.
System.TypeLoadException: There is no implementation of the GetItem method in the type "Microsoft.AspNetCore.Mvc.Razor.Internal.FileProviderRazorProjectFileSystem" from assembly "Microsoft.AspNetCore.Mvc.Razor, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60".
в Microsoft.Extensions.DependencyInjection.MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngineServices(IServiceCollection services)
в Microsoft.Extensions.DependencyInjection.MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder builder)
в Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddMvc(IServiceCollection services)
в Crud.Startup.ConfigureServices(IServiceCollection services) в C:\source\repos\Crud\Crud\Startup.cs:строка 38
--- End the stack trace from the previous location where the exception occurred ---
в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
в Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
в Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
в Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
в Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: There is no implementation of the GetItem method in the type "Microsoft.AspNetCore.Mvc.Razor.Internal.FileProviderRazorProjectFileSystem" from assembly "Microsoft.AspNetCore.Mvc.Razor, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60".
No application service provider was found.
Finding DbContext classes in the project...
Found DbContext 'EmployeeContext'.
Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'EmployeeContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 ---> System.MissingMethodException:There are no parameterless constructors defined for this object..
в System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
в System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
в System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
в System.Activator.CreateInstance(Type type, Boolean nonPublic)
в System.Activator.CreateInstance(Type type)
в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.c__DisplayClass13_3.b__13()
--- End trace of internal exception stack ---
в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.c__DisplayClass13_3.b__13()
в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory)
в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)
в Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
в Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType)
в Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.c__DisplayClass0_0.b__0()
в Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.c__DisplayClass3_0`1.b__0()
в Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to create an object of type 'EmployeeContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
Я не понимаю, что не так. Я попытался сделать простой CRUD в .NET Core MVC с очень простой моделью, которая имеет несколько полей. < /p> Это мои модели: < /p> [code] public class Employee { [Key] public int EmployeeId { get; set; }
[Required] public string FistName { get; set; }
[Required] public string LastName { get; set; }
public int PositionId { get; set; } public virtual Position Position { get; set; }
} public class Position { [Key] public int PositionId { get; set; } public string PositionName { get; set; } public ICollection Employees { get; set; } } < /code> Тогда я сделал контекст приложения: < /p> public class EmployeeContext : DbContext { public EmployeeContext(DbContextOptions options) : base(options) { }
public DbSet Employees { get; set; } public DbSet Positions { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() .HasOne(e => e.Position) .WithMany() .HasForeignKey(e => e.PositionId); } } < /code> и зарегистрированный контекст в startup.cs: < /p> public void ConfigureServices(IServiceCollection services) { services.Configure(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; });
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); } < /code> может потребоваться еще один файл кода .csproj и program.cs < /p>
net461 full
all runtime; build; native; contentfiles; analyzers; buildtransitive
all runtime; build; native; contentfiles; analyzers; buildtransitive
public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); }
public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup(); } < /code> Затем я попытался сделать сначала мигрировать, но я вижу очень странную ошибку add -migration FirstInit -verbose < /p> Using project 'Crud'. Using startup project 'Crud'. Build started... Build succeeded. C:\.nuget\packages\microsoft.entityframeworkcore.tools\3.1.2\tools\net461\win-x86\ef.exe migrations add FirstInit --json --verbose --no-color --prefix-output --assembly C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe --startup-assembly C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe --project-dir C:\source\repos\Crud\Crud\ --language C# --working-dir C:\source\repos\Crud --root-namespace Crud Using assembly 'Crud'. Using startup assembly 'Crud'. Using application base 'C:\source\repos\Crud\Crud\bin\Debug\net461'. Using working directory 'C:\source\repos\Crud\Crud'. Using root namespace 'Crud'. Using project directory 'C:\source\repos\Crud\Crud\'. Using configuration file 'C:\source\repos\Crud\Crud\bin\Debug\net461\Crud.exe.config'. Using assembly 'Crud'. Using startup assembly 'Crud'. Using application base 'C:\source\repos\Crud\Crud\bin\Debug\net461'. Using working directory 'C:\source\repos\Crud\Crud'. Using root namespace 'Crud'. Using project directory 'C:\source\repos\Crud\Crud\'. Finding DbContext classes... Finding IDesignTimeDbContextFactory implementations... Finding application service provider... Finding Microsoft.Extensions.Hosting service provider... Using environment 'Development'. System.TypeLoadException: There is no implementation of the GetItem method in the type "Microsoft.AspNetCore.Mvc.Razor.Internal.FileProviderRazorProjectFileSystem" from assembly "Microsoft.AspNetCore.Mvc.Razor, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60". в Microsoft.Extensions.DependencyInjection.MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngineServices(IServiceCollection services) в Microsoft.Extensions.DependencyInjection.MvcRazorMvcCoreBuilderExtensions.AddRazorViewEngine(IMvcCoreBuilder builder) в Microsoft.Extensions.DependencyInjection.MvcServiceCollectionExtensions.AddMvc(IServiceCollection services) в Crud.Startup.ConfigureServices(IServiceCollection services) в C:\source\repos\Crud\Crud\Startup.cs:строка 38 --- End the stack trace from the previous location where the exception occurred --- в System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() в Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services) в Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices() в Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize() в Microsoft.AspNetCore.Hosting.WebHostBuilder.Build() An error occurred while accessing the Microsoft.Extensions.Hosting services. Continuing without the application service provider. Error: There is no implementation of the GetItem method in the type "Microsoft.AspNetCore.Mvc.Razor.Internal.FileProviderRazorProjectFileSystem" from assembly "Microsoft.AspNetCore.Mvc.Razor, Version=2.2.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60". No application service provider was found. Finding DbContext classes in the project... Found DbContext 'EmployeeContext'. Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'EmployeeContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 ---> System.MissingMethodException:There are no parameterless constructors defined for this object.. в System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) в System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) в System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) в System.Activator.CreateInstance(Type type, Boolean nonPublic) в System.Activator.CreateInstance(Type type) в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.c__DisplayClass13_3.b__13() --- End trace of internal exception stack --- в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.c__DisplayClass13_3.b__13() в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(Func`1 factory) в Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType) в Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(String name, String outputDir, String contextType) в Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(String name, String outputDir, String contextType) в Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration.c__DisplayClass0_0.b__0() в Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.c__DisplayClass3_0`1.b__0() в Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action) Unable to create an object of type 'EmployeeContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728 [/code] Что не так с этими 3 строками?
Я не понимаю, что не так.
Я пытался сделать простой crud в .net core mvc с очень простой моделью с небольшим количеством полей.
Это мои модели:
public class Employee
{
public int EmployeeId { get; set; }
Я не понимаю, что не так.
Я пытался сделать простой crud в .net core mvc с очень простой моделью с небольшим количеством полей.
Это мои модели:
public class Employee
{
public int EmployeeId { get; set; }
Произошла ошибка при доступе к службам Microsoft.Extensions.Hosting. Продолжаем без поставщика услуг приложений. Ошибка: не удалось загрузить конфигурацию
У меня есть фоновая служба, которая выполняет некоторые задачи и задания в долго выполняющемся потоке. Для простоты мы будем рассматривать это как планировщик, который выполняет асинхронный вызов SQL и повторяет его. Теперь я использую AsyncLocal...