. NET Core Entity Framework Core how do you create DbContext and entitydbcontext

Source: Internet
Author: User

. NET Core Entity Framework Core how do you create DbContext and entitydbcontext

This article is copyrighted by the blog and the author Wu Shuang. You are welcome to repost it. for reprinting and crawlers, please indicate the original address of the snail bait in the blog garden at http://www.cnblogs.com/tdws/p/5874212.html.

I am planning to share a series of practical background architectures of. NET Core recently. So I will first introduce EF Core. At present, we share with you various domestic forums that use EF Core at the Web layer based on Microsoft official documents. Of course, this is not a problem, because I also want to share it from the document. The only difference is that the DbContext method is called in the Dal layer. EF6.x you used previously. If you can create a new object in the test code, you can also create an object in the formal project development when you control the uniqueness in the context thread. But! You cannot do this in EF Core.

In EF6.x, your context class is like this, and there is no parameter in the constructor.

You createdUnique within a threadThe context method may be like this.

After reviewing EF6.x and earlier versions, we will go to the body of this article. English official documentation address https://docs.efproject.net/en/latest/platforms/aspnetcore/existing-db.html #

First, I created a. NET Core WebApplication, ConsoleApp, and several. NET Core class libraries. Now I will start with a BLL and DAL class libraries.

The solution is as follows:

EF Core. SqlServer and design are installed on nuget in the class library, ConsoleApp, and WebApi. You can use nuget visual management or nuget console commands. The command is as follows:

Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

In addition, you also need to use the following command to install the tool. Modify project. json of the Dal-layer class library project and add tools nodes.

Install-Package Microsoft.EntityFrameworkCore.Tools –Pre

 "tools": {    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"  }

 

 

Because it is DB First, you also need to create your test database, as shown below.

Next, on the nuget console of the Dal layer where you want to add EF, run the following command to connect to the database. Do not forget to modify the information:

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=AppDb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

This is my configuration.

 Scaffold-DbContext "Server=2013-20150707DJ\SQL2012EXPRESS;Database=AppDb;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

Of course, if you directly execute this section, you will surely encounter an error similar to the following. Since your startup project is Web, you have not referenced the project yet, so it tells you that you cannot find DAL. dll.

The solution is, of course, the UI references BLL and BLL references DAL, and then re-generates the code and runs the command again. If you are prompted to restore your dotnet restore, run the command.

 

After the success, you will find a Model folder in the DAL layer, map your database tables to entity classes, and DbContext classes.

Next, let's take a look at how to handle 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 out 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;");        }

The modification is as follows:

        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)        //{        //    #warning To protect potentially sensitive information in your connection string, you should move it out 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;");        //}        public AppDbContext(DbContextOptions<AppDbContext> options)            : base(options)        { }

Make the following changes in your WebAPI or Startup. cs of your MVC. In its ConfigureServices method, add the following code and modify the connection string:

  services.AddApplicationInsightsTelemetry(Configuration);
  var connection = @"Server=2013-20150707DJ\SQL2012EXPRESS;Database=AppDb;Trusted_Connection=True;"

Execute the following code to add code. It seems to be no different from EF6.x. The only difference is that the DbContext object automatically injects IOC into the constructor dependency for us through the. NET Core framework.

At this point, dbContext is successfully operated in Web/WebApi. So what if you want to operate on the Dal layer? This _ dbContext has no dependency injection. Who will give us the object? We have a new one, but our constructor is there. We can operate on it instead of simply New.

When you really plan to create a new one, you find that you need an object of DbContextOption <AppDbContext>.

Let's create a New DbContextOption <T> object. You can see that the overload requires this parameter.

Overload: You generally Initialize an instance and use the override DbContext. OnConfiguring method, or DbContextOptionBulider <T> to create an instance. Because the object we need is a generic DbContextOption <T> object, the overload method of the former is not a generic type. It may also be that I used it incorrectly. If you have a good implementation, leave a suggestion.

 1  public class UserDal 2     { 3         static string connection = @"Server=2013-20150707DJ\SQL2012EXPRESS;Database=AppDb;Trusted_Connection=True;"; 4         static DbContextOptions<AppDbContext> dbContextOption = new DbContextOptions<AppDbContext>(); 5         static DbContextOptionsBuilder<AppDbContext> dbContextOptionBuilder = new DbContextOptionsBuilder<AppDbContext>(dbContextOption); 6         AppDbContext _dbContext = new AppDbContext(dbContextOptionBuilder.UseSqlServer(connection).Options); 7         public int AddUser() 8         { 9             _dbContext.Users.Add(new Users { Name = "ws4", Email = "wscoder@outlook.com" });10             return _dbContext.SaveChanges();11         }12     }

Called in ConsoleApp, added successfully

 

If you want to share your feedback, I would like to give you some help.

For long-term sharing, click here. Happy Mid-Autumn Festival!

I have a Red Bull and tea at night, and I am not sleepy until five o'clock AM ., A graduate student often told me, have you ever seen Xi'an at a.m? Now I have a sleep. I woke up and asked him if he had seen Suzhou.

Finally, I have a question. Does EF Core currently support Code First? No relevant documents.

 

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.