The entity Framework core of. NET Core

Source: Internet
Author: User

This article copyright belongs to the blog park and the author Wu Di Common All, welcome reprint, reprint and Reptile Please indicate the blog Park snail original address http://www.cnblogs.com/tdws/p/5874212.html.

Recently, we are going to share a series of. NET Core Utility backend architectures, so we'll start with EF core. At present, all the major forums in China, Daniel's share is to follow the official Microsoft document, the Web layer directly applied EF Core. Of course this is not a problem, because I also want to share from the document. The only thing that is more is calling the DbContext method in the DAL layer. You used the ef6.x, if in the test code you can directly new out, in the formal project development, you control the context thread within the unique, you can also new object. But! you can't do this in EF core.

in the ef6.x , in your context class, there are no parameters in the constructor method.

Perhaps this is the way you create a unique context within a thread .

Reviewing the ef6.x and previous versions, enter the text of this share below. English Official document Address https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html#

First I create a new. NET Core Webapplication,consoleapp and a few. NET Core class libraries, let's start with a Bll,dal two class library.

The solution is as follows:

EF core.sqlserver and design are installed from NuGet in the class library and ConsoleApp and WEBAPI. You can also manage the NuGet console commands through NuGet Visual management. The command is as follows:

Install-package Microsoft.EntityFrameworkCore.SqlServer
Install-package Microsoft.EntityFrameworkCore.SqlServer.Design

You will also need to install the tool using the command below. and modify the Project.jsonof the DAL Layer Class Library project to increase the tools node.

Install-package Microsoft.entityframeworkcore.tools–pre

" Tools " : {    "Microsoft.EntityFrameworkCore.Tools""1.0.0- Preview2-final"  }

Because it's DB first, you'll also create your test database, like so.

Next, in the NuGet console where you want to add the DAL layer of EF, execute the following command to connect the database information, and don't forget to modify:

" server= (localdb) \mssqllocaldb;database=appdb; Trusted_connection=true; " Microsoft.entityframeworkcore.sqlserver-outputdir Models

This is my configuration.

" server=2013-20150707dj\sql2012express;database=appdb; Trusted_connection=true; " Microsoft.entityframeworkcore.sqlserver-outputdir Models

Of course the direct execution of this paragraph, you will certainly encounter a similar error. Since your startup project is the Web, currently you have not done the references that the project should have, so it tells you that you can't find DAL.dll.

The workaround is, of course, that the UI reference bll,bll the DAL, regenerate it and execute the command again. And if you're prompted to dotnet restore, then you can do it a bit.

After success you will find that the DAL layer has more than one model folder and maps your database tables out to entity classes, plus the DbContext class.

Next look at how to deal with your dbcontext. Miscrosoft tells us that we need to modify the following code.

protected Override void onconfiguring (Dbcontextoptionsbuilder optionsbuilder)        {            #warning to protect potentially sensitive information in your connection string, you should move it OU T of source code. See http://go.microsoft.com/fwlink/?linkid=723263 for guidance on storing connection strings.             optionsbuilder.usesqlserver (@ "server=2013-20150707dj\sql2012express;database= appdb; Trusted_connection=true; " );        }

This is done after the modification:

        //protected override void Onconfiguring (Dbcontextoptionsbuilder optionsbuilder)//{        //#warning to protect potentially sensitive information in your connection string, your should move it out of source Code. Seehttp://go.microsoft.com/fwlink/?LinkId=723263For guidance on storing connection strings. //optionsbuilder.usesqlserver (@ "SERVER=2013-20150707DJ\SQL2012EXPRESS;DATABASE=APPDB; Trusted_connection=true; ");//}         PublicAppdbcontext (dbcontextoptions<appdbcontext>options):Base(options) {}

Make the following changes to your WEBAPI or your MVC Startup.cs. In its Configureservices method, add the following code, connection string still remember to modify:

Services. Addapplicationinsightstelemetry (Configuration);
var connection = @ "SERVER=2013-20150707DJ\SQL2012EXPRESS;DATABASE=APPDB; Trusted_connection=true; "

Do the following to add code, look and ef6.x no difference. The only difference is that the DbContext object is automatically injected into the IOC by the. NET Core framework for our constructor dependencies.

Here we operate DbContext successfully in WEB/WEBAPI. So what if you want to operate on the DAL layer? This _dbcontext without the dependency injection, who will give us the object? Own new one, but our constructors are placed there, not simply new to operate.

When you really set out to start the new one, you find that you need a dbcontextoption<appdbcontext> object.

Then we're new to a Dbcontextoption<t> object. You see that the overload requires this parameter.

Overloading says: You typically initialize an instance using the Override Dbcontext.onconfiguring method, or use dbcontextoptionbulider<t> to create an instance. Because the object we want is a generic dbcontextoption<t> object, the overloaded method of the former is not a generic type. It may be that I use the wrong, if you have a good implementation, please leave a suggestion.

1   Public classUserdal2     {3         Static stringConnection =@"server=2013-20150707dj\sql2012express;database=appdb; Trusted_connection=true;";4         StaticDbcontextoptions<appdbcontext> dbcontextoption =NewDbcontextoptions<appdbcontext>();5         StaticDbcontextoptionsbuilder<appdbcontext> Dbcontextoptionbuilder =NewDbcontextoptionsbuilder<appdbcontext>(dbcontextoption);6Appdbcontext _dbcontext =NewAppdbcontext (Dbcontextoptionbuilder.usesqlserver (connection). Options);7          Public intAddUser ()8         {9_dbcontext.users.add (NewUsers {Name ="Ws4", Email ="[email protected]" });Ten             return_dbcontext.savechanges (); One         } A}

Called in ConsoleApp, adding success

If I share a bit, you have a bit of help, welcome to praise, but also for your own harvest praise.

Long-term sharing, welcome to click below attention. Wish you a happy Mid-Autumn Festival!

Drink a Red Bull and have some tea at night, not sleepy until five o'clock in the morning ... Waist pain. , a graduate student friend often told me, have you ever seen XI ' an in the three o'clock in the morning? Now get some sleep and wake up and ask him if he's seen the five o'clock in the morning Suzhou.

Finally, I have a question, does EF core currently support code first? No documentation is visible.

The entity Framework core of. NET Core

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.