【发布时间】:2023-04-05 07:17:01
【问题描述】:
在处理 Code First (EF 4.3) 时,有没有办法从 DbSet<T> 处理 List<T>,然后将更改保存到列表中?
例如...
class Program {
static void Main(string[] args) {
Database.SetInitializer(new DropCreateDatabaseAlways<Context>());
Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
using (Context c = new Context()) {
// Works
c.Entities.Add(new Entity());
// Doesn't work
List<Entity> entities = c.Entities.ToList();
entities.Add(new Entity());
// Somehow attach the new unattached elements?
c.SaveChanges();
Console.WriteLine(c.Entities.Count()); // Prints 1
Console.ReadLine();
}
}
}
class Context : DbContext {
public DbSet<Entity> Entities { get; set; }
}
class Entity {
public int Id { get; set; }
public int Foo { get; set; }
}
有没有办法可以做到这一点?
【问题讨论】:
标签: c# .net entity-framework ef-code-first dbcontext