C # Use the EF frame in SQL Server

vs2017, sqlserver2017 (localdb) debugging passed.
Create database d1 in sqlserver, table t1 is as follows:
share picture

Enter the data as follows:
Share pictures

Create any Project, here is the console as an example.
Add data model Model1:
Share pictures

To minimize Write the code and select the following content (this mode seems to have no migration problem, which is good):
Share a picture

Note: The connection string can be set in the code, so “No” is selected below and the check box is not checked.
Share a picture

Select the table you want to use:
Share pictures
Finish

Model1.cs and t1.cs are automatically added to the project. One is a database object (including a table), and the other is a record object in the table.
Share a picture

Put the’base(“name =Model1”)’ is changed to a connection string:
share picture

< p>You can see the attributes and classes declared in two files, one for the table and the other for the record.
Share pictures

At this point, complete the model and database part, you can write the main The procedure is up. The code and effects are as follows:

static void  Main(string[] args)

{
Model1 m
= new Model1();// Declare the database object m
//Use linq statements to filter records. Similar to select * from t1
var students = from x in m.t1 select x;
//Use lamda expressions to filter out the records that meet the conditions span>
t1 student = m.t1.First(x => x.nl> 18) ;
foreach (var item in students)
{
Console.WriteLine($
"{item.xm} { item.nl} {item.cj1} {item.xb}");
}
Console.WriteLine($
"{student.xm} { student.nl} {student.cj1} {student.xb}");
Console.ReadKey();
}

Share pictures

static void  Main(string[] args)

{
Model1 m
= new Model1();// Declare the database object m
//Use linq statements to filter records. Similar to select * from t1
var students = from x in m.t1 select x;
//Use lamda expressions to filter out the records that meet the conditions span>
t1 student = m.t1.First(x => x.nl> 18) ;
foreach (var item in students)
{
Console.WriteLine($
"{item.xm} { item.nl} {item.cj1} {item.xb}");
}
Console.WriteLine($
"{student.xm} { student.nl} {student.cj1} {student.xb}");
Console.ReadKey();
}

Leave a Comment

Your email address will not be published.