[英]How can I reattach a List to DbSet?
When dealing with Code First (EF 4.3), is there a way to work with a List<T>
from a DbSet<T>
, and then persist the changes to the list? 在处理Code First(EF 4.3)时,是否可以使用
DbSet<T>
的List<T>
进行DbSet<T>
,然后将更改持久保存到列表中?
For example... 例如...
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; }
}
Is there a way that I can do this? 有办法可以做到吗?
In this trivial example, you could do something like this. 在这个简单的示例中,您可以执行以下操作。
foreach(Entity entity in entities)
{
var entry = c.Entry(entity);
if (entry.State == EntityState.Detached)
{
c.Entities.Add(entry);
}
}
However, this probably won't work in a more complex scenario. 但是,这在更复杂的情况下可能行不通。 There are a couple of different ways to solve this.
有两种不同的方法可以解决此问题。
Entity.Id == 0
, assuming that Id starts at 1. Entity.Id == 0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.