We generally add, delete, query, and update basic operations for data. This article takes the code in the previous article as an example to briefly introduce how to use basic operations in Entity Framework.
Query
1. query using a linq statement
Var query = from B in db. Blogs
Where B. BlogId = 1 & B. Name = "my blog"
Select B;
Var blog = query. FirstOrDefault ();
The advantage of this method is that it can use very complex query conditions like SQL statements, which is very powerful for complex queries.
2. Use the Find function to query through the primary key
Var blog = db. Blogs. Find (1 );
This method is similar to the lexicographic query, where data is queried through the primary key. It is the most commonly used method. When you use Find to query, if the specified Primary Key cannot query the result, null is returned and no exception is thrown.
Add:
Db. Blogs. Add (new
Blog () {BlogId = 2, Name = "test2 "});
Db. SaveChanges ();
The add operation is the same as our operation set, but here we need to call the SaveChanges function to keep the change to the database.
Update:
Var blog = db. Blogs. Find (1 );
Blog. Name = "test1 ";
Db. SaveChanges ();
There are three steps to update: query data, modify data, and save results.
Delete:
Var blog = db. Blogs. Find (1 );
Db. Blogs. Remove (blog );
Db. SaveChanges ();
There are also three steps to delete data: query data, delete data, and save results. Note that if the null function is input in Remove, an exception is thrown.
Batch Delete and update:
Batch deletion and batch update are rarely used in common set operations, but they are very common in SQL operations. Theoretically, we can use Lambda expressions to elegantly implement this operation, but EntityFramework does not support it. You can only delete it by executing SQL statements. This is also a constant criticism of EntityFramework.
However, thanks to the flexible and powerful Syntax of C #, some people have implemented this function by using extended functions. If you are interested, refer to Lao Zhao's article on batch data deletion using Lambda Expression, I will not talk about it here.