Thursday, March 14, 2019

Setting up Entity Framework Core for MVC Database First Application

So far we have seen simple examples using Asp.Net MVC to display static messages and static list of model objects, however complex applications will have to deal with database display and update data from the database. In the previous versions of .Net / MVC we used Entity Framework to interact with the database with .Net Core we will use Entity Framework Core to interact with the database. In this post we shall see on how to set up EF core to interact with the database.

First step to setup EFCore is to create a Models folder, let us create a folder EFCoreModel in the project. Next we need to add the following 3 NuGet packages to the project we can do this either using Package Manager GUI or Package Manager console.


Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.SqlServer.Design
Microsoft.EntityFrameworkCore.Tools





In this sample we will use an Existing database (Database First) approach, so we need to execute a command to generate the Entity classes from the existing DB. We can run this command either from the package manager console or from a command prompt.

In this sample we will run the following command from the package management console to generate Entity classes from the database
UserRegistration. Notice that we mention the Models folder Models/EFCoreModel in the command, this will generate the entity classes in the Models folder.

Scaffold-DbContext "Server=<ServerName>\SQLEXPRESS;Database=UserRegistration;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/EFCoreModel

Once the command executes successfully the Entity classes will be generated inside in the model folder as follows.





By default the connection string for the database will be added to the Context file UserRegistrationContext.cs, but this is not recommended hence we will mode the connection string to a config file.

Open the config file appsettings.json and add a connection string property as follows
{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "i.": null,
    "UserRegistrationDatabase": "Server=<servername>\\SQLEXPRESS;Database=UserRegistration;Trusted_Connection=True;"
  }
}

Next we need to configure the application to use the connection string from the config file, we will do this in the ConfigureServices() method of Startup.cs file as follows.

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });


    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    services.AddDbContext<UserRegistrationContext>(options => options.UseSqlServer(Configuration.GetConnectionString("UserRegistrationDatabase")));
}

That’s it we are done with setting up Entity Framework Core for our MVC application. We can now create Controllers and Views to interact with the database.


Search Flipkart Products:
Flipkart.com

No comments: