My Problem is the following. I have a DataAccessLayer Project with a DalClass. In this Dal class I have many Methods for operations with Entity Framework. For example some pseudo-code to show how we do it.
class DalClass
{
public void SetEntityObject(EntityObject entityObject)
{
using (var context = new Entities())
{
context.EntityObjectSet.Attach(entityObject);
context.ChangeTracker.DetectChanges();
foreach (var entity in context.ChangeTracker.Entries())
{
entity.State = entityObject.EntityState;
}
context.SaveChanges();
}
}
public EntityObject GetEntitObject(Guid id)
{
EntityObject result;
using (var context = new Entities())
{
result = context.EntityObjectSet.Where(x => x.Id == Id);
}
return result;
}
}
Each time we do operations with EF we create a new instance context and do some work. My problem is that I have a method in my DalClass to get a List of EntityObjects Like this :
public List<EntityObject> GetEntityObjectsByIds(List<Guid> idList)
{
using (var context = new Entities())
{
var query = from entityObject in context.EntityObjectSet
where idList.Contains(entityObject.Id)
select entityObject;
return query.ToList();
}
}
After I return the List to my Business Layer class. I do some changes to each EntityObject, calculations, change some Property values and so on. After that I call a method from my BusinessLayer class to save the new edited List with this method:
public void UpdateEntityObjects(List<EntityObject> newEntityObjectList)
{
using (var context = new Entities())
{
var idList = entityObjectList.Select(x => x.Id).ToList();
var query = from entityObject in context.EntityObjectSet
where idList.Contains(entityObject.Id)
select entityObject;
var entityObjectList = query.ToList();
entityObjectList = newEntityObjectList;
context.ChangeTracker.DetectChanges();
foreach (var entity in context.ChangeTracker.Entries())
{
entity.State = EntityState.Modified;
}
context.SaveChanges();
}
}
Problem I can not save newEntityObjectList that I Edited in my BusinessLayer. Obviously this is not working.
entityObjectList = newEntityObjectList;
So how is the best way to save the newEntityObjectList ?
Problem I have to fier this query twice
var query = from entityObject in context.EntityObjectSet where idList.Contains(entityObject.Id) select entityObject;
Solution to 2. Problem could be if I use one Context instance for GetEntityObjectsByIds() and UpdateEntityObjects(). But in all our Dal Classes we avoided that. Even if I use one instance of Context class, this does not solve Problem 1. So how can I save newEntityObjectList ?