我正在开发一个asp.net mvc4应用程序,其中实现了存储库和工作单元模式。我想要一些解决方案从存储库中获取新添加的数据意味着我希望能够在保存到数据库之前操作数据。
我了解到这些对象在EF更改跟踪机制中可用,因此它们应该可用,即使它尚未保存到数据库中。记住这一点只是做下面的事情
以下是我的控制器......
Public void save(Order orderdata)
{
if(orderdata.Id > 0)
{
....
....
.... // after validating the data's I will be calling the Save() service method which i mentioned below.
save(orderdata,false); //Calling service method to attach data to repository
}
//after attaching the orderdata to reposistory i am calling a private method to modify above freshly added orderdata(i.e., orderdata which is recently added into repository but not saved into database)
UpdateOrder(order)
}
以下是我的私人方法......
private void UpdateOrder(Order order)
{
if (order != null)
{
var orderRequest = GetOrderRequest<Order>(x => x.TrackingNumber == order.TrackingNumber); //calling GetOrderRequest() service method which i mentioned below
if (orderRequest != null)
{
...
...// after some validations only i need to assign a status to newly added order.
orderRequest.Status = "assigned";
}
}
}
}
以下是我的服务方法实施......
public void Save(Order obj, bool Commit = true)
{
if (obj.Id > 0)
{
// Adding Order obj to repository.
OrderRepository.Attach(obj);
}
else
OrderRepository.Add(obj);
// Note: While I am calling my save() service method am passing commit as 'False' in order to prevent it from saving into database so that after some transaction i will finally save all the data into database.
if (Commit)
Commit();
}
public IQueryable<T> GetOrderRequest<T>(Expression<Func<T, bool>> predicate = null) where T : WorkRequest
{
var query = OrderRepository.FindAll().OfType<T>();
if (predicate != null)
query = query.Where(predicate);
return query; //Here I am expecting the newly added data
}
现在我的问题是我想访问存储库中新添加的数据以更新我的订单状态。但我无法这样做,因为GetOrderRequest返回始终为null。我做错了什么或者是否有任何其他方式从存储库中获取新添加的实体。请给我一些建议...
答案 0 :(得分:0)
我在Respository
类中使用它来访问上下文中的内容。
并不意味着它不存在。只是意味着它在上下文中。
但这对你来说仍然足够了。
如果是数据库生成的ID,则按密钥访问具有挑战性;-)
但是否则该集合非常有用。
// ef offers Local property, handy to see inside context.
public ObservableCollection<TPoco> Local {
get { return Context.Set<TPoco>().Local; }
}
所以你现在可以离开......
repository.Local.Where(t=>t.field == 'X' )