是否可以看到添加的实体从一个未保存EF4背景?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了是否可以看到添加的实体从一个未保存EF4背景?相关的知识,希望对你有一定的参考价值。
我刚刚进入实体框架4,并最终希望把它包在使用波苏斯存储库模式。我发现,我并没有期待,虽然东西。看来,如果你创建一个上下文对象添加到它(不保存的情况下),并再次查询的背景下,它不会在结果中包括新的对象。难道我做错了什么?现在看来似乎应该返回我已经添加了什么,即使我已经没救了,结果回数据库呢。这里是我的示例代码:
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
答案
一个L2E查询始终从数据库返回的实体。它将基于查询的MergeOption
内存的变化将它们合并。
要看到添加的实体,看看上下文:
var addedCustomers = from se in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added)
where se.Entity is Customer
select se.Entity;
另一答案
使用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);
}
}
以上是关于是否可以看到添加的实体从一个未保存EF4背景?的主要内容,如果未能解决你的问题,请参考以下文章