[英]How can I reattach a List to DbSet?
在處理Code First(EF 4.3)時,是否可以使用DbSet<T>
的List<T>
進行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; }
}
有辦法可以做到嗎?
在這個簡單的示例中,您可以執行以下操作。
foreach(Entity entity in entities)
{
var entry = c.Entry(entity);
if (entry.State == EntityState.Detached)
{
c.Entities.Add(entry);
}
}
但是,這在更復雜的情況下可能行不通。 有兩種不同的方法可以解決此問題。
Entity.Id == 0
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.