Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use EF SQLite to add, delete, modify and check the database by ASP.NET Core

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail how ASP.NET Core uses EF SQLite to add, delete, modify and check the database. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

1 New ASP.NET Core MVC Application 1.1 New MVC Application

Open Visual Studio 2017, create a new ASP.NET Web application, and select MVC (Model View Controller).

1.2 introduction of NuGet package

Need to introduce

Microsoft.EntityFrameworkCore

Microsoft.EntityFrameworkCore.Sqlite

Introduction of tutorial

Click

Dependency item

-right click

-- manage NuGet packages

Take turns to enter and install microsoft.EntityFrameworkCore and Microsoft.EntityFrameworkCore.Sqlite, with the following procedure

Note:

Please choose a version that is similar to your own ASP.NET Core version.

The author's version is ASP.NET Core version 2.1, and the NuGet package version chosen is 2.11.

If your .net Core is up to date, then NuGet can choose the latest one as well.

If you choose a version and find an error, you can go to NuGet to delete the installation again.

When prompted for an update, do not update.

2 create a new model and context

This step builds the model and context, and then the database and database tables will be generated according to the code here!

You need to create a context class and a model class to include the model class in the context class, and the model class contained in the context class will generate the corresponding database table.

The following code does not need to operate on its own, just need to look at it. (note the notes)

Using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.EntityFrameworkCore;namespace WebApplication1.Models {public class SqlContext:DbContext {public SqlContext (DbContextOptions Options): base (Options) {} public DbSet A {get; set;} / / generate data table A} public class A {public int ID {get; set in the database }} public class B {public int ID {get; set;}

In the above code, there are three classes

Where SqlContext class is the context class

Classes An and B are model classes.

However, only A generates database tables, while B does not.

Both An and B are model classes, because database tables can be generated, so A can also be called entity class. Because B has no DbSet, B is called model class, not entity class.

Class A will generate a table in a real database with a corresponding relationship, so it is an "entity class".

Class B has no corresponding existence, just a model, no actual objects, so it is only called "model class".

2.1 New Model Class

The above code puts the model class and the context class in the same file SqlContext.cs, which is not very readable.

Because a model class represents a data table, the context class is equivalent to a configuration class, a database has dozens of tables, and each table has several columns, which makes the file content too complex.

We can reduce the coupling, there is only one class per class file, each class represents a table, you want to create several tables, write a few classes.

Actual operation

In the Models folder

Create a new class Users.cs

Write code directly in the class

Public int ID {get; set;} / / Primary key public string Name {get; set;} / / user name public int Age {get; set;} / / user age public int Number {get; set;} / / user mobile number

As shown in the picture

Note:

A model class corresponds to a data table (Table)

A property of the model class corresponds to a column.

Model classes should only have properties, not methods, and so on.

The author only writes one table here. If you want more than one table, you can create another class and add it to the context class.

2.2 New context

The model class has been established above, and the model class will become the data table (Table) itself. However, they cannot directly generate data tables and need context to map model classes to data tables, otherwise they are just ordinary classes.

Create a new class MyContext.cs in the Models directory

Introduce EF (EntityFrameworkCore) into the header

Using Microsoft.EntityFrameworkCore

Override the MyContext class

Step 1 public class MyContext is changed to public class MyContext:DbContext / / to indicate that this class is a context class, and the database name is My. What is the name of the class, that is why the database name is step 2.

Write a constructor in the MyContext class

Public MyContext (DbContextOptions options): base (options) {}

This constructor involves dependency injection, so I won't go into it here, just know that this constructor can configure the relevant settings.

The constructor here is empty because there is nothing to configure for the time being.

Step 3

Add code under the constructor to map the model class.

Public DbSet Uaa {get; set;} / / Dbset is mapped to a table / / Dbset. The Users in the table is the name generated in the database by the model class / / Uaa Users class used.

Note:

The above code means that a table named Uaa is generated in the database based on the model class Users.

A context corresponds to a database, and the first part of the context class MyContext,Context will become the database name. For example, asdwadaaContext, will generate the database asdwadaa.

A model class corresponds to a data table (Table)

The complete code is as follows

Using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.EntityFrameworkCore;namespace WebApplication1.Models {public class MyContext:DbContext {public MyContext (DbContextOptions options): base (options) {} public DbSet Uaa {get; set;}}

Preview of the resulting effect picture

3 configure the service

In order for the application to generate and use the database, you need to add code to the Startup.cs

Introduce three libraries in the header

Using WebApplication1.Models; / / different using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Sqlite may be named

Then inject services into the application in the following ways

(we'll explain the function later, but we don't need to add it now.)

1 write string directly

Add code to Startup.cs

String connecttext = "Filename=F:\\ MY.DB"; services.AddDbContext (options= > options.UseSqlite (connecttext)); 2 using JSON

Add content to the appsettings.json file (comments section)

{"Logging": {"LogLevel": {"Default": "Warning"}, "AllowedHosts": "*", / / comment part "ConnectionStrings": {"MyContext": "Filename=F:\\ MY.DB" / / comment part}}

Then add code to Startup.cs

String connecttext = Configuration.GetConnectionString ("MyContext"); services.AddDbContext (options= > options.UseSqlite (connecttext))

Note:

In the above two ways, the function of the connecttext variable is to get the database connection string, which has no special meaning, just to increase readability.

The connection string of SQLite, just write "Filename= [absolute path]"

Services.AddDbContext (options= > options.UseSqlite (connection string))

Express

Injects DbContext (database context service) into the application, and the injected context type is MyContext >

(options= > options.UseSqlite (connection string)

Is a lambda expression that indicates that a sqlite database is used and the parameter is a connection string. Lambda expressions belong to the basics of C #. If not, remember first and look for information later.

To actually operate.

Please copy the code in method one above, and then add it to the Startup.cs class-- ConfigureServices method.

Copy the following code directly to overwrite ConfigureServerices

Public void ConfigureServices (IServiceCollection services) {services.Configure (options = > {/ / This lambda determines whether user consent for non-essential cookies is needed for a given request. Options.CheckConsentNeeded = context = > true; options.MinimumSameSitePolicy = SameSiteMode.None;}); string connecttext = "Filename=F:\\ MY.DB"; services.AddDbContext (options = > options.UseSqlite (connecttext)); services.AddMvc (). SetCompatibilityVersion (CompatibilityVersion.Version_2_1);}

Note:

SQLite database file, can not add a suffix name, but add a suffix name will be easy for others to identify this is a database file, the suffix name is not limited, can be .DB, .SQLite, SQLite3 and so on.

4 generate database

Click

Tools

-NuGet package Manager

-- package Manager console

Input

Add-Migration InitialCreate

At the end of the wait, enter

Update-Database

As shown in the picture

Then you will find that the solution Manager has an extra Migrations directory and some files, and a MY.DB file in the F:\ directory.

5 use tools to manage SQLite files

After generating the database file, you will find that it cannot be opened directly, even if it is VS2017.

At this point you can use the tool SQLite Expert Professional to manage the SQLIte database.

Download address https://www.yisu.com/database/265.html

Software introduction https://www.yisu.com/database/265.html

After installing the software, you can open the database file.

Software Open Database File tutorial:

6 generate add, delete, query and modify base frame

At this time, you can operate on the database in the program, for how to use, it is best to see Microsoft Entity Framework documents.

The author gives a simple example here.

Step 1

In the Controller directory, right-click to add-- the project to create a new base.

Step 2

Click on the view to use Entity Framework's MVC controller

Select Users ([project name] .models) for the model class

Database context selection MyContext ([project name] .models)

Click add

Step 3

At this time, you can see

Controller has more UsersController.cs files.

Views has more Users directory.

Please click run or press F5 to start the website

Add Users to the back of the website

For example, https://localhost:[ actual port] / Users, you can do whatever you want with the Users table.

Step 4 add data

Click Create new

Result

7 fill in the data cannot be empty

Note: this involves features, data verification, the author will not repeat, readers can first understand, and then translate other articles.

After the above operation, we have been able to operate on the database, in fact, although we can manipulate the data, but if I want to set an item to be filled in, the format of an item must be a mobile phone? You can't let users fill it in casually, can you?

Open Users.cs

Add referenc

Using System.ComponentModel.DataAnnotations

The code to modify the Users class is as follows

Public class Users {public int ID {get; set;} / / Primary key [Required] public string Name {get; set;} / n / user name [Required (ErrorMessage = "cannot be empty")] public int Age {get; set } / / user age [Required] [Regular_Expression (@ "^ 1 [3458] [0-9] {9} $", ErrorMessage = "incorrect mobile number format")] public int Number {get; set;} / / user mobile number}

Run the website, open URL/Users, click Create New, and then submit without filling in the content, you will find that

Fill in other items, and then fill in a number in Number, you will find that

This is model verification.

It doesn't need to write any code, just add [feature] to the attribute.

Please refer to this knowledge separately.

Note:

[Required] indicates that the item cannot be empty

[Required (ErrorMessage = "cannot be empty")] ErrorMessage = "" means that if you do not fill in according to this requirement, an amount prompt will appear.

[Regular_Expression (@ "^ 1 [3458] [0-9] {9} $", ErrorMessage = "incorrect mobile number format")] this is regular expression verification, and an error will appear if the filled in does not conform to the format.

About ASP.NET Core how to use EF SQLite to add, delete, modify and check the database is shared here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report