[英]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>
不会以任何方式“连接”到DbSet
, DbContext
或数据库。
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();
}
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.