Learn EF Core in one step (1.DBFirst)

Source: Internet
Author: User

Preface

Haven't written a blog for a long time, because really busy, finally empty, intend to learn EF core by the way to write a series, today we will take a look at the first article Dbfirst.

This article environment: VS2017 Win7. NET Core1.1 EF Core1.1.2

Body

Here we do not discuss whether to use Dbfirst good, or Codefirst high-end. Each has its own use and application scenarios.

We simply have to use this dbfirst.

Since it is dbfirst, then before using Dbfirst. First you have to have a database (well, nonsense)

Second, if you are a Windows7 system then you need to upgrade your Windows PowerShell to 3.0+ version

Then you need to install the relevant toolkit, which can be downloaded from NuGet as follows:

To make it easier for you to copy. Let me make a list:

Microsoft.entityframeworkcore

Microsoft.EntityFrameworkCore.SqlServer

Microsoft.EntityFrameworkCore.Tools

Microsoft.EntityFrameworkCore.Design

Microsoft.EntityFrameworkCore.SqlServer.Design

Then, in the tool options for VS, select NuGet Package Manager, Select Package Management Console

Enter the command line:

" Enter your database connection string here " Microsoft.EntityFrameworkCore.SqlServer

A modles folder will be generated:

This is where your context object and the associated entity class are.

We go into the context object and find that our connection string is cured in this face:

Of course we can't do that, so please remove him.

Next, we use ASP. NET Core to test the test to see if we can access it.

The process of creating a core project, I won't say it.

Then add references to your core project with NuGet: Microsoft.EntityFrameworkCore.SqlServer and Microsoft.entityframeworkcore

Add the database connection string in the configuration file:

  " ConnectionStrings " : {    "schoolconnection"""Data source=.;i Nitial catalog=school_test; User id=**; password=***; Multipleactiveresultsets=true"  }

Then we inject our context object into the startup:

Injected in the Configureservices () method, the code is as follows:

         Public voidconfigureservices (iservicecollection services) {//ADD Framework Services. //inject signalr. (not relevant to this article, please disregard)Services. ADDSIGNALR (options ={options. Hubs.enabledetailederrors=true;           }); //Inject Context ObjectServices. adddbcontext<school_testcontext> (options =options. Usesqlserver (Configuration.getconnectionstring ("Schoolconnection"))); Services.        Addmvc (); }

We create the controller with the following code:

     Public class Testcontroller:controller    {        // Constructor Injection context        Private ReadOnly school_testcontext _context;          Public TestController (school_testcontext Context)        {            = Context;        }          Public iactionresult ListView ()        {            return  View (_context. Usertable.tolist ());        }    }

Create the corresponding view as follows:

@model IEnumerable<Efcoremodel. Modles.usertable>@{viewdata["Title"] = "ListView";    Layout = "~/views/shared/_layout.cshtml";} <H2>Listview</H2><P>    <aasp-action= "Create">Create New</a></P><Tableclass= "Table">    <thead>        <TR>            <th>User name</th>            <th>Password</th>            <th>ID</th>            <th>class name</th>            <th></th>        </TR>    </thead>    <tbody>@foreach (var item in Model) {<TR>                <TD>@Html. displayfor (ModelItem = Item. UserName)</TD>                <TD>@Html. displayfor (ModelItem = Item. PassWord)</TD>                <TD>@Html. displayfor (ModelItem = Item. ID)</TD>                <TD>@Html. displayfor (ModelItem = Item. Class.classname)</TD>                <TD>                    <aasp-action= "Edit"Asp-route-id= "@item. Id ">Edit</a> | <aasp-action= "Details"Asp-route-id= "@item. Id ">Details</a> | <aasp-action= "Delete"Asp-route-id= "@item. Id ">Delete</a>                </TD>            </TR>        }    </tbody></Table>

Running the code will cause an error. The following errors:

No database provider have been configured for this DbContext. A provider can configured by overriding the Dbcontext.onconfiguring method or by using Adddbcontext on the application Service provider. If Adddbcontext is used, then also ensure that your DbContext type accepts a Dbcontextoptions<tcontext> object in it s constructor and passes it to the base constructor for DbContext.

This is because the context that we generate through Dbfirst is not directly injected into use. We need to retrofit and add constructors to the context as follows:

         Public School_testcontext (dbcontextoptions options):base(options)        {        }

Then run our code. The results are as follows:

We found that the red box position as the association table of the class name, and did not show ~, this is left for us to explain later.

Learn EF Core in one step (1.DBFirst)

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.