簡體   English   中英

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

[英]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);
     }
}

但是,這在更復雜的情況下可能行不通。 有兩種不同的方法可以解決此問題。

  1. 如果從數據庫自動分配了ID,則可以假設Id從1開始,檢查Entity.Id == 0
  2. 如果您是手動分配ID,則可以查詢表以查看ID是否不存在。
  3. 您可以自行決定跟蹤事實之后添加了哪些記錄。 這可以通過第二個列表。 您可以擁有自己的State屬性,該屬性不會映射到數據庫。 如果將實體投影到特定於應用程序的模型上,這會更容易。
  4. 或者,您可以將其同時添加到列表和上下文中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM