【问题标题】:How can I reattach a List to DbSet?如何将列表重新附加到 DbSet?
【发布时间】:2023-04-05 07:17:01
【问题描述】:

在处理 Code First (EF 4.3) 时,有没有办法从 DbSet<T> 处理 List<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; }
}

有没有办法可以做到这一点?

【问题讨论】:

    标签: c# .net entity-framework ef-code-first dbcontext


    【解决方案1】:

    在这个简单的例子中,你可以做这样的事情。

    foreach(Entity entity in entities)
    {
         var entry = c.Entry(entity);
    
         if (entry.State == EntityState.Detached)
         {
             c.Entities.Add(entry);
         }
    }
    

    但是,这可能不适用于更复杂的场景。有几种不同的方法可以解决这个问题。

    1. 如果 Id 是从数据库自动分配的,您可以检查是否为 Entity.Id == 0,假设 Id 从 1 开始。
    2. 如果您手动分配 Id,您可以查询表以查看 Id 是否不存在。
    3. 以某种方式,您决定跟踪哪些记录是事后添加的。这可以通过第二个列表。您可以拥有自己的不映射到数据库的 State 属性。如果您将实体投影到特定于应用程序的模型上,这会更容易。
    4. 或者您可以同时将其添加到您的列表和上下文中。

    【讨论】:

    • 这些都是很好的建议,谢谢。示例代码也非常有用。
    • 这里的“c”是什么,既没有你初始化也没有赋值,它是从哪里来的。
    • @AshishJain 这与问题中的“c”相同。这并不是一个完整的例子,只是大致的方向。
    • 谢谢,在发表我的评论后,我在 2 小时后再次查看;)无论如何,我还有一点,如果您的实体为空,那么您将如何解决这个问题?
    猜你喜欢
    • 2011-12-09
    • 2015-08-05
    • 1970-01-01
    • 2016-05-06
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    相关资源
    最近更新 更多