是否可以从未保存的EF4上下文中看到添加的实体?

时间:2010-09-02 13:57:56

标签: entity-framework entity-framework-4

我刚刚进入实体框架4,最终希望使用POCO将其包装在存储库模式中。我发现了一些我没想到的东西。看来,如果您创建上下文,向其添加对象(不保存上下文)并再次查询上下文,则它不会在结果中包含新对象。难道我做错了什么?它似乎应该返回我添加的内容,即使我还没有将结果保存回数据库。这是我的示例代码:

  ShopEntities context = new ShopEntities();

  // there is only 1 customer so far
  var customers = from c in context.Customers
              select c;

  Console.WriteLine(customers.Count()); // displays 1

  Customer newCustomer = context.Customers.CreateObject();
  newCustomer.FirstName = "Joe";
  newCustomer.LastName = "Smith";

  context.Customers.AddObject(newCustomer);

  var customers2 = from c in context.Customers
               select c;

  Console.WriteLine(customers2.Count()); // still only displays 1

  context.SaveChanges();

  var customers3 = from c in context.Customers
               select c;

  Console.WriteLine(customers3.Count()); // only after saving does it display 2

2 个答案:

答案 0 :(得分:5)

L2E查询始终从数据库返回实体。它将根据查询的MergeOption将其与内存中的更改合并。

要查看添加的实体,请查看上下文:

var addedCustomers = from se in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added)
                     where se.Entity is Customer
                     select se.Entity;

答案 1 :(得分:0)

使用ChangeTracker属性:

   public delegate void SaveEventHandler(Dictionary<EntityState, List<IAuditable>> entities);
   public event SaveEventHandler OnReturnAuditableEntitiesAfterSaveEvent;

public override Task<int> SaveChangesAsync()
    {
        try
        {
            if (OnReturnAuditableEntitiesAfterSaveEvent != null)
            {
                List< EntityState > states = new List<EntityState>()
                {
                    EntityState.Added,
                    EntityState.Deleted,
                    EntityState.Modified
                };

                Dictionary<EntityState, List<IAuditable>> entities = new Dictionary<EntityState, List<IAuditable>>();

                List<DbEntityEntry> unsavedEntities = ChangeTracker.Entries()
                    .Where(p => p.Entity is IAuditable && states.Contains(p.State))
                    .ToList();

                foreach (var state in states)
                {
                    List<DbEntityEntry> list = unsavedEntities.Where(c => c.State == state).ToList();
                    if (list.Count > 0)
                    {
                        switch (state)
                        {
                            case EntityState.Added:
                            case EntityState.Deleted:
                                entities.Add(state, list.Select(c=> c.Entity as IAuditable).ToList());
                                break;

                            case EntityState.Modified:
                                List<IAuditable> modifiedAntities = new List<IAuditable>();
                                //Check for modified entities if the value has changed
                                foreach (var entry in list)
                                {
                                    foreach (var prop in entry.OriginalValues.PropertyNames)
                                    {
                                        var originalValue = entry.OriginalValues[prop].ToString();
                                        var currentValue = entry.CurrentValues[prop].ToString();
                                        if (originalValue != currentValue)
                                        {
                                            modifiedAntities.Add(entry.Entity as IAuditable);
                                        }
                                    }
                                }

                                if (modifiedAntities.Count > 0)
                                    entities.Add(state, modifiedAntities);
                                break;

                            default:
                                break;
                        }
                    }
                }

                if (entities.Count > 0)
                    OnReturnAuditableEntitiesAfterSaveEvent.Invoke(entities);
            }

            return base.SaveChangesAsync();
        }
        catch (DbEntityValidationException ex)
        {
            throw CollectValidationErrors(ex);
        }
    }