1. 简介
每个上下文实例都有一个 ChangeTracker, 它负责跟踪需要写入数据库的更改. 更改实体类的实例时, 这些更改会记录在 ChangeTracker 中, 然后在调用 SaveChanges 时会被写入数据库中. 此数据库提供程序负责将更改转换为特定于数据库的操作 (例如, 关系数据库的 INSERT,UPDATE 和 DELETE 命令).
2. 基本保存
了解如何使用上下文和实体类添加, 修改和删除数据.
2.1 添加数据
使用 DbSet.Add 方法添加实体类的新实例. 调用 SaveChanges 时, 数据将插入到数据库中.
- using (var context = new BloggingContext())
- {
- var blog = new Blog { Url = "http://sample.com" };
- context.Blogs.Add(blog);
- context.SaveChanges();
- }
2.2 更新数据
EF 将自动检测对由上下文跟踪的现有实体所做的更改. 这包括从数据库加载查询的实体, 以及之前添加并保存到数据库的实体. 只需通过赋值来修改属性, 然后调用 SaveChanges 即可.
- using (var context = new BloggingContext())
- {
- var blog = context.Blogs.First();
- blog.Url = "http://sample.com/blog";
- context.SaveChanges();
- }
2.3 删除数据
使用 DbSet.Remove 方法删除实体类的实例. 如果实体已存在于数据库中, 则将在 SaveChanges 期间删除该实体. 如果实体尚未保存到数据库 (即跟踪为 "已添加"), 则在调用 SaveChanges 时, 该实体会从上下文中移除且不再插入.
- using (var context = new BloggingContext())
- {
- var blog = context.Blogs.First();
- context.Blogs.Remove(blog);
- context.SaveChanges();
- }
2.4 单个 SaveChanges 中的多个操作
可以将多个添加 / 更新 / 删除操作合并到对 SaveChanges 的单个调用.
- using (var context = new BloggingContext())
- {
- // add
- context.Blogs.Add(new Blog { Url = "http://sample.com/blog_one" });
- context.Blogs.Add(new Blog { Url = "http://sample.com/blog_two" });
- // update
- var firstBlog = context.Blogs.First();
- firstBlog.Url = "";
- // remove
- var lastBlog = context.Blogs.Last();
- context.Blogs.Remove(lastBlog);
- context.SaveChanges();
- }
3. 保存关联数据
除了独立实体以外, 还可以使用模型中定义的关系.
3.1 添加关联数据
- using (var context = new BloggingContext())
- {
- var blog = new Blog
- {
- Url = "http://blogs.msdn.com/dotnet",
- Posts = new List<Post>
- {
- new Post { Title = "Intro to C#" },
- new Post { Title = "Intro to VB.NET" },
- new Post { Title = "Intro to F#" }
- }
- };
- context.Blogs.Add(blog);
- context.SaveChanges();
- }
- using (var context = new BloggingContext())
- {
- var blog = context.Blogs.Include(b => b.Posts).First();
- var post = new Post { Title = "Intro to EF Core" };
- blog.Posts.Add(post);
- context.SaveChanges();
- }
- using (var context = new BloggingContext())
- {
- // 新增一个主体实体
- var blog = new Blog { Url = "http://blogs.msdn.com/visualstudio" };
- var post = context.Posts.First();
- //post 更新关系
- post.Blog = blog;
- context.SaveChanges();
- }
- var blog = context.Blogs.Include(b => b.Posts).First();
- var posts = blog.Posts.ToList();
- DumpEntities("After loading entities:", context, blog, posts);
- context.Remove(blog);
- DumpEntities($"After deleting blog'{blog.BlogId}':", context, blog, posts);
- try
- {
- Console.WriteLine();
- Console.WriteLine("Saving changes:");
- context.SaveChanges();
- DumpSql();
- DumpEntities("After SaveChanges:", context, blog, posts);
- }
- catch (Exception e)
- {
- DumpSql();
- Console.WriteLine();
- Console.WriteLine($"SaveChanges threw {e.GetType().Name}: {(e is DbUpdateException ? e.InnerException.Message : e.Message)}");
- }
- After loading entities:
- Blog '1' is in state Unchanged with 2 posts referenced.
- Post '1' is in state Unchanged with FK '1' and reference to blog '1'.
- Post '2' is in state Unchanged with FK '1' and reference to blog '1'.
- After deleting blog '1':
- Blog '1' is in state Deleted with 2 posts referenced.
- Post '1' is in state Unchanged with FK '1' and reference to blog '1'.
- Post '2' is in state Unchanged with FK '1' and reference to blog '1'.
- Saving changes:
- DELETE FROM [Posts] WHERE [PostId] = 1
- DELETE FROM [Posts] WHERE [PostId] = 2
- DELETE FROM [Blogs] WHERE [BlogId] = 1
- After SaveChanges:
- Blog '1' is in state Detached with 2 posts referenced.
- Post '1' is in state Detached with FK '1' and no reference to a blog.
- Post '2' is in state Detached with FK '1' and no reference to a blog.
- using (var context = new BloggingContext())
- {
- using (var transaction = context.Database.BeginTransaction())
- {
- try
- {
- context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" });
- context.SaveChanges();
- context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/visualstudio" });
- context.SaveChanges();
- var blogs = context.Blogs
- .OrderBy(b => b.Url)
- .ToList();
- // Commit transaction if all commands succeed, transaction will auto-rollback
- // when disposed if either commands fails
- transaction.Commit();
- }
- catch (Exception)
- {
- // TODO: Handle failure
- }
- }
- }
来源: https://www.cnblogs.com/wzk153/p/12449538.html