Emmm, originally wanted to use the core to do a small project to play, and then must be used to the database,
Then think, ah, need not codefirst, feel very greasy harm appearance, so, a face innocence I stepped into a bottomless sinkhole ...
Originally thought, should not be difficult, more Baidu is good, spicy how many gods have written a tutorial,
Fragmented spent nearly three weeks, according to the demo wrote n many times I have to give up the struggle,
Invited a big guy working together, watching him crackling debugging for half an hour later, the database that appeared, inexplicable heart plug,
The big guy is the big guy, forgive the younger brother I Caishuxueqian, so make a note first, keep the spare.
I will write a blog, while doing a simple demo, in fact, many times we lack of, is these entry-level things,
The code that adds a variety of validations and functions will affect the code that we find needed.
Tool: VS2017
Environment:. Net Core 2.0, EF7
first, we need to build a solution, a class library project, and a Web project
The construction of these projects should be jiangzi.
After the build, it is a small key, we have to add EF dependency, how to add it?
See a lot of methods on the net, basically is to use the tool =>nuget package Management +/package management console, to add dependencies, presumably Jiangzi:
Can be open first, to be useful later, but I think this is a bit of trouble, so directly written in the project file (*.csproj), to write the code is as follows
1 <ItemGroup>2 <packagereference include=" Microsoft.EntityFrameworkCore.SqlServer "version="2.0.1 "/>3 <packagereference include="Microsoft.EntityFrameworkCore.Tools" version="2.0.1" />4 </ItemGroup>
Once saved, models's EF dependency has been added, how do you know if it's successful? Look here
Previously there was only one SDK, now there is a nuget, there are two things, and no warning ah those messy things, it means no problem,
Likewise, we have a Webfront project, plus a dependency, and here's not,,,
As we go this far, we should start creating the context and data tables for the database.
Create a database context class (Dbcodefirst) and a data table class (Dt_user) with the following structure
The contents of Dbcodefirst are as follows:
1 Public classDbcorefirst:dbcontext2 {3 PublicDbcorefirst ():Base()4 {5 6 }7 8 PublicDbcorefirst (dbcontextoptions<dbcorefirst>options)9:Base(Options)Ten { One A } - - Override protected voidonconfiguring (Dbcontextoptionsbuilder optionsbuilder) the { - Base. Onconfiguring (Optionsbuilder); - } - + #regionData Sheet - + PublicDbset<dt_user> Dt_user {Get;Set; } A at #endregion - -}
? The contents of Dt_user are as follows:
1 Public classDt_user2 {3 /// <summary>4 ///default int type ID is primary key5 ///You must have a field as the primary key, or you will get an error6 /// </summary>7 Public intID {Get;Set; }8 Public stringUserName {Get;Set; }9}
Then write a piece of code in the Configureservices method of the startup class of the Webfornt project, what database name is written in the connection string , what is the database name generated, Can be inconsistent with your context class name
At this time, we will look at the database situation, there is no dbcodefirst this library
The play is over, remember the openingPackage Management Console ?
Open it, enter the command, add-migration * * * * * * * * * * * * * *
1 add-migration Dbcorefirst
In the execution of it, I reported several mistakes, listed
First error
genericarguments[0'Models.Migrations.DBCoreFirst ' Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory ' 1[tcontext]' Tcontext'.
genericarguments [0], "model. Migration. Dbcorefirst ', ' Microsoft. Entityframeworkcore. Design. Idesigntimedbcontextfactory ' 1 [tcontext] ' violates the type's tcontext constraint.
This error pot in the picture, I use red box up the place, the default project , yes, yes, that is, it should be changed to WEBFONRT,
After the change, we continue to execute add-migration dbcorefirst .
Followed by a second mistake.
' Webfront ' is ' Models ' the assembly "Webfront" could not be loaded. Make sure it is referenced by the "Models" of the Startup Project.
This error pot, see the tail of my arrow, where? is the models project, now this project is bold, indicating that it is a startup project,
Change the startup project for the Webfornt project, very good, the second pit was filled by me, continue to run add-migration Dbcorefirst
A third pit ensued.
' Webfront ' doesn' Models '. Either change your target project or the change your migrations assembly. your target project Webfront does not migrate component model matching. Either change the target project or change the migration assembly.
In fact, this pit is not too big, forcibly down can also generate a database, but, for me this obsessive-compulsive disorder, where to allow the next floating red?
So Baidu, after reviewing the relevant information, I know where the problem is, is the tail of the arrow 28th line of code
Services. adddbcontext<dbcorefirst> (options = options. Usesqlserver (connection)); Change to services. Adddbcontext<DBCoreFirst> (Options and options). Usesqlserver (connection, C = c.migrationsassembly ("webfront"));
Very good, no floating red, however, in the picture of the yellow box, will correspond to generate some files,
As I understand it, these files are not log files, they are used for data table mapping, so these files should appear in models instead of Webfront
A series of Baidu, as if not to find, only their own point of point,
Found a fourth pit.
First, restore the code,
Services. adddbcontext<dbcorefirst> (options = options. Usesqlserver (CONSTR));
Then we go back to the first pit, change the default item from "Webfront" to "Models"
Then execute add-migration dbcorefirst
Very stable, now four places are right, and then we look at the database, this time has not generated the corresponding library
Then we execute the second paragraph of the order Update-database
Then, luckily, I met the fifth pit again.
genericarguments[" models.migrations.dbcorefirst " , ON " microsoft.entityframeworkcore.design.idesignti Medbcontextfactory ' 1[tcontext] " violates the constraint of type ' 1 [tcontext] ' violates the type's tcontext constraint.
Open a file generated by the command to see
Two classes of names a hair, the database is based on Dbcodefirst this class to generate, no problem on the hell,
So, why does the class name on the left be the same as the right one?
The problem is that we execute the "add-migration dbcoedfirst" command.
add-Migration Dbcodefirst Change to add-migration DBLog
After the implementation of the effect, it is obvious that the change
Immediately, execute the command "update-database"
Then we go to the database to see
Very stable, the database generated, EF will automatically generate __efmigrationshistory table, as if it is used to record the data migration log, we now ignore it.
At this point, EF7 's Codefirst generation database is complete,
Self-feeling, finish this article, I play Mosaic technology is more and more stable,,,
Complete codefirst using. Net core+ef7