在处理 Code First (EF 4.3) 时,有没有办法使用 a List<T>
from a DbSet<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; }
}
有没有办法我可以做到这一点?