简体   繁体   English

插入记录实体框架

[英]Insert a record Entity framework

So I was trying to insert a record in a database using entity Framework well I tried this simple code 所以我试图使用实体框架在数据库中插入一条记录,我尝试了这个简单的代码

TestEntities DB = new TestEntities();
List<Article> Articles = BD.Articles.ToList();
Articles.Add(new Article() { Id = 0, Category = "Category1",  Title = "Title1"});
Articles.Add(new Article() { Id = 0, Category = "Category2", Title = "Title2" });
DB.SaveChanges();

The records got added to the Articles list but not to the database can someone please explain to me how does this work. 记录已添加到“文章”列表中,但未添加到数据库中,有人可以向我解释此工作原理。

Articles is just an in-memory copy of the DbSet . Articles只是DbSet的内存副本。 You should add the items to the DbSet as well if you want to be able to persist them to the database: 如果您希望能够将它们持久保存到数据库中,也应该将它们添加到DbSet中:

var art = new Article() { Id = 0, Category = "Category1",  Title = "Title1"};
Articles.Add(art);
BD.Articles.Add(art);

The List<Article> is not "connected" to the DbSet , DbContext nor the database in any way. List<Article>不会以任何方式“连接”到DbSetDbContext或数据库。

using(TestEntities DB = new TestEntities())
{
    BD.Articles.Add(new Article() { Id = 0, Category = "Category1",  Title = "Title1"});
    BD.Articles.Add(new Article() { Id = 0, Category = "Category2", Title = "Title2" });
    DB.SaveChanges();
}
  1. Add the new article to the DbSet, not the retrieved List which is just an in memory representation. 将新文章添加到DbSet中,而不是将获取的List添加到内存中的表示形式中。
  2. Always wrap your types that implement IDisposable in using statements. 始终在using语句中包装实现IDisposable的类型。 In this case it ensures that the db connection is closed when the code exists. 在这种情况下,它确保在代码存在时关闭数据库连接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM