EFCore connects to database

EF core learning records (.netCore database connection and some operations)

1. Create a context connection pool AppDbContext

Function: One of the links with the database, which can be understood as creating a database named AppDbContext

code show as below:

public class AppDbContext : DbContext

{

public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)

{

}

public DbSet<Employer> Employers { get; set; }

}

This can be understood in the code:

AppDbContext can be understood as a database in the database

Employers can be understood as a table under the database

Configure through the constructor and pass the configuration file to the parent class to configure the connection.

2. Create interface

The reason is that there may be more than one database, or there may be several. At this time, the interface needs to be configured in the startUp class to determine which database the front desk should call.

The interface code is as follows:

interface IEmployerRepository

{

/// <summary>

/// Get student information by ID

/// </summary>

/// <param name="id"></param>

/// <returns></returns>

Employer GetEmployer(int id);

IEnumerable<Employer> getAllEmployers();

Employer Add(Employer employer);

Employer Update(Employer employer);

Employer Delete(int id);

}

The StartUp class configuration is as follows:

public void ConfigureServices(IServiceCollection services)

{

//services.AddPooledDbContextFactory<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EmployerConnection")));

services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EmployerConnection")));

services.AddScoped<IEmployerRepository,SQLEmployerRepository>(); //Bind the interface to the database

services.AddControllersWithViews().AddRazorRuntimeCompilation();

}

This is the sentence

services.AddScoped<IEmployerRepository,SQLEmployerRepository>();

1

If the time database is changed, just change the SQLEmplyerRepository.

3Create a class that inherits this interface to query the corresponding database

code show as below

public class SQLEmployerRepository : IEmployerRepository

{

private readonly AppDbContext context;

public SQLEmployerRepository(AppDbContext context)

{

this.context = context;

}

public Employer Add(Employer employer)

{

context.Employers.Add(employer);

context.SaveChanges();

return employer;

}

public Employer Delete(int id)

{

Employer employer = context.Employers.Find(id);

if(employer != null)

{

context.Employers.Remove(employer);

context.SaveChanges();

}

return employer;

}

public IEnumerable<Employer> getAllEmployers()

{

return context.Employers;

}

public Employer GetEmployer(int id)

{

return context.Employers.Find(id);

}

public Employer Update(Employer UpdateEmployer)

{

var employer = context.Employers.Attach(UpdateEmployer);

employer.State = Microsoft.EntityFrameworkCore.EntityState.Modified;

context.SaveChanges();

return UpdateEmployer;

}

}

There is also an important link that needs to be configured

It was mentioned earlier that the configuration should be passed to the parent class for configuration, but the configuration file information has not been configured yet, so you need to configure it in the startup class.

code show as below

public IConfiguration Configuration { get; } //Define configuration variables

public Startup(IConfiguration configuration)

{

Configuration = configuration;//The configuration information passed in during the instance, that is, Configuration obtains the configuration information

}

// This method gets called by the runtime. Use this method to add services to the container.

public void ConfigureServices(IServiceCollection services)

{

//services.AddPooledDbContextFactory<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EmployerConnection")));

services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EmployerConnection")));

services.AddScoped<IEmployerRepository,SQLEmployerRepository>(); //Bind the interface to the database

services.AddControllersWithViews().AddRazorRuntimeCompilation();

}

Among them, the following sentence (two sentences, one pool and one factory pool) is the middleware that configures the transmission of configuration information.

//services.AddPooledDbContextFactory<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EmployerConnection")));

services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("EmployerConnection")));

Explanation: services.AddDbContextPool

Configure AppDbContext (database) connection through generics

解释:options => options.UseSqlServer(Configuration.GetConnectionString(“EmployerConnection”))

Tell the program to configure the connection string in SQL server mode, where the connection string is Configuration.GetConnectionString("EmployerConnection")

5Configure the connection string

Configure in appSetting, as shown in the following code

{

"AllowedHosts": "*",

"ConnectionStrings": {

"EmployerConnection": "server=(localdb)\\MSSQLLocalDB;database=AppDbContext;Trusted_Connection=true"

},

"Logging": {

"LogLevel": {

"Default": "Information",

"Microsoft": "Warning",

"Microsoft.Hosting.Lifetime": "Information"

}

}

}

Among them, the following sentence is

"ConnectionStrings": {

"EmployerConnection": "server=(localdb)\\MSSQLLocalDB;database=EmployDb;Trusted_Connection=true"

},

6Inject in Controller

The code is as follows, injected through the constructor, so that it can be used in the controller

private readonly IEmployerRepository employerRepository;

public ScanController(IEmployerRepository employer) => employerRepository = employer;

Guess you like

Origin blog.csdn.net/2201_75837601/article/details/128677369