Const Const -4 years ago 107
C# Question

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" });

The records got added to the Articles list but not to the database can someone please explain to me how does this work.

Answer Source

Articles is just an in-memory copy of the DbSet. You should add the items to the DbSet as well if you want to be able to persist them to the database:

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

The List<Article> is not "connected" to the DbSet, DbContext nor the database in any way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download