简体   繁体   English

如何将列表重新附加到DbSet?

[英]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. 有两种不同的方法可以解决此问题。

  1. If the Id is auto assigned from the database, you could check if Entity.Id == 0 , assuming that Id starts at 1. 如果从数据库自动分配了ID,则可以假设Id从1开始,检查Entity.Id == 0
  2. If you are assigning the Id manually, you could query the table to see if the Id does not exist. 如果您是手动分配ID,则可以查询表以查看ID是否不存在。
  3. Keep track, somehow, you decide, of which records were added after the fact. 您可以自行决定跟踪事实之后添加了哪些记录。 This could be through a second list. 这可以通过第二个列表。 You could have your own State property which does not map to the database. 您可以拥有自己的State属性,该属性不会映射到数据库。 This is easier if you project your entities on to application specific models. 如果将实体投影到特定于应用程序的模型上,这会更容易。
  4. Or you could just add it to your list and the context at the same time. 或者,您可以将其同时添加到列表和上下文中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM