rainbowShiningUnicorn rainbowShiningUnicorn -4 years ago 171
ASP.NET (C#) Question

ASP.NET Entity FrameWork remove() + ToList()

There is a list of managers (in fact a history), where current is marked as property with

TillDate == null
and
IsIsCurrentManager = true
.

db.MyManagers.Remove(db.MyManagers
.Where(e => e.ProjectId == projectId
&& e.MyManagerId == Id).First());
var newCurrentManager = db.MyManagers
.Where(e => e.ProjectId == projectId)
.OrderByDescending(i => i.FromDate)
.FirstOrDefault();
newCurrentManager.TillDate = null;
newCurrentManager.IsCurrentManager = true;
db.SaveChanges();


The problem is that
Remove()
method will only mark entity as
deleted
, but, as far as i can see, it still will be added to the list. How can deleted 1 record and than build a list of managers without it, without using
SaveChanges()
2 times or hardcoding
MyManagerList[2]

Answer Source

It's important to remember that Entity Framework is just an interface into your data store and all you are usually doing is building queries, queries that don't actually run until you materialise the results of a select (i.e. by enumerating through the results or calling something like ToList() or Single()) or, in the case of an update/delete operation, when you call SaveChanges().

So while you can do something like checking that the entity is tracked in the context as a deleted item, you are probably much better off sending the results to the database by calling SaveChanges() twice.

The secondary benefit of that is that another query that doesn't use the same context object (e.g. another web request) will be able to see that the item has been deleted while the original query is trying to pull the list of managers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download