. NET uses the DAO. NET object class model to operate the database, .netdao.net
1. Create a project
Open vs2017 and create a new project named orm1
2. Create a database
Open SqlServer database, create database orm1, and create table student.
3. Create an ADO. NET Object Data Model
Click Create connection to create a database connection. In fact, the server name input represents the local server. The default Windows authentication is used for authentication.
Select the created database orm1.
Remember the connection name orm1Entities, which will be used for subsequent code writing.
Check the table here.
Click OK. the following warning may pop up. Just click OK.
The following view is displayed. At this point, the DAO. NET object type model is created successfully.
Click Generate in VS and then regenerate the project. On the console, enter:
4. Create An aspx File
Create An aspx file webform1.aspx
<% @ Page Language = "C #" AutoEventWireup = "true" CodeBehind = "WebForm1.aspx. cs" Inherits = "orm1.WebForm1" %> <! DOCTYPE html>
Now we can write the database code using the Dao. NET Entity type model in the cs file.
1. Show All
void ShowAll() { var db = new orm1Entities(); GridView1.DataSource = db.Student.ToList(); GridView1.DataBind(); }
Do you still remember orm1Entities? Have you seen it before creating an object-class model?
2. Search for Data
protected void Select_Click(object sender, EventArgs e) { var db = new orm1Entities(); var item = db.Student.Where(M => M.sid == sid.Text).ToList(); GridView1.DataSource = item; GridView1.DataBind(); }
Where M is any character.
3. Add data
protected void Add_Click(object sender, EventArgs e) { var db = new orm1Entities(); var item = new Student { sid = sid.Text, sname = sname.Text, sage = int.Parse(sage.Text) }; db.Student.Add(item); db.SaveChanges(); ShowAll(); }
4. delete data
Protected void Delete_Click (object sender, EventArgs e) {var db = new orm1Entities (); var item = db. student. where (M => M. sid = sid. text ). firstOrDefault (); if (item! = Null) {db. Student. Remove (item); db. SaveChanges (); ShowAll () ;}else {Response. Write ("no user ");}}
5. modify data
Protected void Update_Click (object sender, EventArgs e) {var db = new orm1Entities (); var item = db. student. where (M => M. sid = sid. text ). firstOrDefault (); if (item! = Null) {item. sname = sname. text; item. sage = int. parse (sage. text); db. saveChanges (); ShowAll ();} else {Response. write ("This user is not ");}}