EntityFrameworkCore v1.1.1 problem summary, entityframeworkcore

Source: Internet
Author: User

EntityFrameworkCore v1.1.1 problem summary, entityframeworkcore

With the latest version of Universe 1 IDE released [], AspNetCore and EntityFrameworkCore (Team) both released the latest code.

But in my opinion, these are not the most important. The most important thing is that the dotnet cli has finally been rtm, as well as various tools supporting it. It's so cool that we don't have to worry about beta, preview, final, final-update, and other versions. Although various versions will be released in the future, many usage methods and habits of the tools will be fixed after this release to facilitate the use and memory of such users.

Problem Environment

To keep up with the new version, after installing vs2017, I can't wait to build a project for testing.

Project

Content

EfCore11.Domain Entity type. You do not need to reference other nuget packages.
EfCore11.DataSqlServer DbContext project, which must reference nuget packages such as Microsoft. EntityFrameworkCore. SqlServer
EfCore11.SomeUI AspnetCore MVC project, which can be generated using the dotnet new mvc command

Project files:

The Blog. cs file in the Domain Project

  1 using System.Collections.Generic;  2   3 namespace EfCore11.Domain  4 {  5     public class Blog  6     {  7         public int Id { get; set; }  8         public string Name { get; set; }  9         public string Url { get; set; } 10         public ICollection<Post> Posts { get; set; } 11     } 12 } 13 

The Post. cs file in the Domain Project

  1 namespace EfCore11.Domain  2 {  3     public class Post  4     {  5         public int Id { get; set; }  6         public string Title { get; set; }  7         public string Body { get; set; }  8   9         public int BlogId { get; set; } 10         public Blog Blog { get; set; } 11     } 12 } 13 

BlogDbContext. cs file in DataSqlServer Project

  1 using EfCore11.Domain;  2 using Microsoft.EntityFrameworkCore;  3   4 namespace EfCore11.DataSqlServer  5 {  6     public class BlogDbContext : DbContext  7     {  8         public DbSet<Post> Post { get; set; }  9         public DbSet<Blog> Blog { get; set; } 10  11         public BlogDbContext(DbContextOptions<BlogDbContext> option) 12             : base(option) 13         { 14  15         } 16     } 17 }

Code modified in the Startup. cs file in the SomeUI Project

1 public void ConfigureServices (IServiceCollection services) 2 {3 // Add framework services. 4 services. addMvc (); 5 // The json configuration method is not used here, because it is not the focus of this article. If necessary, please manually baidu 6 string conn = "server = (localdb) \ mssqllocaldb; database = Ef. core; Trusted_connection = true; "; 7 services. addDbContext <BlogDbContext> (opt => opt. useSqlServer (conn); 8}
Question 0: in which project will code first migration be executed?

According to the current project organization, there are two projects that can execute code first migration: DbContext project, DataSqlServer project in the environment described in this article, and Mvc project, which is the SomeUI project in this article.

Both projects can complete the operations required for database migration, but the implementation is different. In which project the migration is completed, it means that the corresponding migration code is maintained in which project, and the MVC project used in the production environment does not contain all the database migration code (for many reasons, no one will put the code that contains the "resume generation event" in the production environment). Therefore, the development project usually uses the DbContext project to manage the migration code, and the test environment is random.

 

To put it simple, migrate in the MVC environment: Problem 1: An error occurred while executing the dotnet ef command.

Reproduction method:CMD open the SomeUI directory and execute the "dotnet ef" command

Error Message: No executable found matching command "dotnet-ef"

Explanation: When ef core is compiled, its content is split into many packages to facilitate programmers to load only the Code required by the program, so that the program will occupy less memory and run faster, easier deployment. To run the dotnet-ef command, you also need to load Microsoft. EntityFrameworkCore. Tools. DotNet

The description of this package is as follows:

Solution: Currently, the dotnet cli does not directly add methods referenced by the command line tool, so it can only be a little violent and directly modify the csproj file:

Add the following directly under the ProjectGroup Tag:

  1   <ItemGroup>  2     <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />  3   </ItemGroup>

// After adding the package, if your vs has some strange phenomena, such as the nuget package is not loaded and the reference is abnormal, you can try to close the current project, open the project again to solve the problem.

// It seems that the project file is not reloaded after modification, and it is expected that the update1 file will be more stable.

Repair check: Execute dotnet ef again. You can see the unicorn.

Question 2: An error is returned when dotnet ef migrations add initial is executed.

Reproduction method:CMD open the SomeUI directory and execute "dotnet ef migrations add initial"

Error message:Cocould not load file or assembly 'Microsoft. EntityFrameworkCore. Design, Culture = neutral, PublicKeyToken = null'. When there are too many other statements about the latest version of the program, there are too many other statements about the program.

Explanation: Same as the previous issue, the error message is clear, that is, there is still a lack of nuget package: Microsoft. EntityFrameworkCore. Design

Solution: Run dotnet add package Microsoft. EntityFrameworkCore. Design to add the package to the cli.

Repair check: Execute dotnet ef migrations add initial again, and the error message is changed:

Problem 3: the Migration reports an error. You must specify the Assembly that contains the migration.

Reproduction method: For details, see question 2.

Error message:Your target project 'xxxxx' doesn' t match your migrations assembly xxxxxxxx'. Either change your target project or change your migrations assembly.

Explanation: The current migration project is inconsistent with the project that contains the DbContext assembly. You can either change the project that executes the migration operation or modify the migration assembly.

Solution: You can select either the two paths, either switch to the DbContext assembly to manage the migration code, or modify the current code to adapt to the migration method. The error message provides a simple solution:

Change your migrations assembly by using DbContextOptionsBuilder. e. g. options. useSqlServer (connection, B => B. migrationsAssembly ("EfCore11.SomeUI ")). 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.

The modified code is the Startup. cs file of the SomeUI project.

1 public void ConfigureServices (IServiceCollection services) 2 {3 // Add framework services. 4 services. addMvc (); 5 // The json configuration method is not used here, because it is not the focus of this article. If necessary, please manually baidu 6 string conn = "server = (localdb) \ mssqllocaldb; database = Ef. core; Trusted_connection = true; "; 7 services. addDbContext <BlogDbContext> (opt => opt. useSqlServer (conn 8, B => B. migrationsAssembly ("EfCore11.SomeUI ")
  9         )); 10 }

Repair check: The Migration command is re-executed successfully.

Then execute "dotnet ef database update" to migrate the database according to the existing code.

So far, the simple code migration process has been completed. However, the solution of the above process can be implemented without dividing it into three projects. If you want to implement a complex project or deploy a solution that is entangled in the environment, you still need to go through the following pitfalls.

 

Use DbContext project migration:

The environment and code changes must be rolled back to issue 0. Then use CMD to open the DataSqlServer directory.

Run the dotnet ef command.Question 1, question 2You can modify it according to the description. However, note that the project has been replaced :)

Question 4: ef tooling's support for. NetStandard

Reproduction method:Execute Code migration in CMD

Error message:Startup project 'efcore11. dataSqlServer. csproj 'Targets framework '. NETStandard '. this framework is not intended for execution and may fail to resolve runtime dependencies. if so, specify a different project using the -- startup-project option and try again.

Explanation: This is not a serious problem, so the error is displayed in yellow. The current version of EF command line tool has limited support for. NetStandard, so a warning message is displayed. If you really want to modify this issue, you can modify the targetFramework to netcoreapp1.1.

 

Problem 5: DbContext cannot be initialized.

Reproduction method:Execute Code migration in CMD

Error message:No parameterless constructor was found on 'blogdbcontext'. Either add a parameterless constructor to 'blogdbcontext' or add an implementation of 'signature <BlogDbContext> 'in the same assembly as 'blogdbcontext '.

Explanation: Because the DbContext in the text does not provide a non-argument constructor, either a non-argument contextfactory is provided or an IDbContextFactory is implemented. Here, the Branch appears again. By convention, it is simple: inject a "'idbcontextfactory <BlogDbContext>" into the mvc program through the-s |-startup-project parameter ", in this way, DbContext can be initialized normally.

The code needs to be modified for relatively complex methods. For details, seeQuestion 6.

Solution: CMD run the "dotnet ef migrations add initialCreate-s .. \ EfCore11.SomeUI" command"

Repair check:

Question 6: Implement DbContext without parameter constructor for Migration

Reproduction method:

Modify the Code:BlogDbContext. cs file of DataSqlServer

1 using EfCore11.Domain; 2 using Microsoft. entityFrameworkCore; 3 4 namespace EfCore11.DataSqlServer 5 {6 public class BlogDbContext: DbContext 7 {8 public DbSet <Post> Post {get; set;} 9 public DbSet <Blog> Blog {get; set;} 10 11 // public BlogDbContext (DbContextOptions <BlogDbContext> option) 12 //: base (option) 13 // {14 15 //} 16 17 // because no parameter constructor is used, the link string 18 protected override void ongrouping (DbContextOptionsBuilder optionsBuilder) 19 {20 optionsBuilder is required. useSqlServer ("server = (localdb) \ mssqllocaldb; database = Ef. core; Trusted_connection = true; "); 21} 22} 23}

Run the following command:Dotnet ef migrations add initialCreate

Run the following command:Dotnet ef database update

Error message:Cocould not load file or assembly 'System. data. sqlClient, Version = 4.1.0.0, Culture = neutral, PublicKeyToken = b03f5f7f11d50a3a '. just a few minutes later.

Or: Cocould not load file or assembly 'System. diagnostics. diagnosticSource, Version = 4.0.1.0, Culture = neutral, PublicKeyToken = cc7b13ffcd2ddd51 '. the located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Explanation: The error message is different because different targetframeworks are used in the DbContext project. If targetFramework = netstandard1.4 is used, the error is that System. Data. SqlClient cannot be loaded.Question 4If targetFramework = netcoreapp1.1 is modified, the error is that System. Diagnostics. DiagnosticSource cannot be loaded.

This problem is really amazing, and it cannot be understood from the error information. At present, the solutions provided by ef team are a bit difficult, and the MVC project is used. I believe this solution is only a temporary solution, and later EF Team will properly handle this problem.

Solution: CMD run the "dotnet ef database update-s .. \ EfCore11.SomeUI" command. // walkaround

Repair check: The SQL statement used to create a database is displayed when the command is executed.

 

The final result is

 

I also want to share a message with my friends in the garden:

Oracle finally responded to developers' requests: The dotnet core-based ODP driver was developed before and after the end of 2017.

For details, see Statement of Direction: ODP. NET on Microsoft. NET Core.

 

Author: soy milk without sugar

Blog: https://www.cnblogs.com/soldout

The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.