I am having a lambda expression which can fetch multiple records from my table.
Here is the expression
public sys_Log_Deposits_Interest_Master GetDepositsPendingRecord(string glCode, int fromDateID)
{
using (var db = new DataClasses1DataContext())
{
var deposit = db.sys_Log_Deposits_Interest_Masters.Where(deposits => deposits.cGLCode.Equals(glCode) && deposits.nFromDateID.Equals(fromDateID));
return deposit;
}
}
I am getting an Error Cannot implicitly convert type IQueryable To Table Object.
I want to return the table object to my Update method which will update some fileds of the result.
Here is my Update method
public void UpdatePendingRecords(string glCode, int fromDateID)
{
using (var db = new DataClasses1DataContext())
{
var deposit = GetDepositsPendingRecord(glCode, fromDateID);
foreach (var pending in deposit)
{
pending.cAuthorizedStatus = "Authorized";
pending.dAuthorizedOn = DateTime.Now;
pending.cAuthorizedBy = HttpContext.Current.User.Identity.Name;
}
}
}
Currently I am not able to get it working.
Can anyone help me with this query?
Any help is much appreciated.
It’s an
IQueryable<T>whereTis whatever typesys_Log_Deposits_Interest_Mastersis a table of. e.g.IQueryable<Log_Deposits_Interest_Master>etc.Note that the table class that
sys_Log_Deposits_Interest_Mastersis an instance of also implements that interface. The result is a different implementation that has information to know that it should take it’s results from there, and also apply the filter in theWhere.You are also disposing of the context in the wrong place, because it won’t exist by the time the values are enumerated through.
In this case, since you are going to work directly on the results rather than apply any further changes to the query, I’d
foreachthrough the results andyieldthem in the method, so it gets turned into an enumeration block and the lifetime gets handled differently. Otherwise I’d either work to make sure the datacontext was alive longer by passing it into that method rather than creating it there, or at a pinch I wouldn’t dispose it (but only at a pinch, while the linq2sql people have said not disposing datacontexts is safe, it goes against good practice – you should really assume that it’s never safe to do that – also, it’s only safe most times; do you want to learn when it is or isn’t? Neither do I. Edit: Today by coincidence brings an example where it wasn’t safe with https://stackoverflow.com/a/12002914/400547).Edit with examples:
Best approach:
If you really had to include datacontext creation within the method called you could do
However this isn’t very useful if you want save the changes you make back to the database, as to do that you must call
SubmitChanges()on the same context that you got them from or else rebind them. It also means that if you were to add anotherWhere()on, or useCount()or anything else that can be passed to the database, it won’t be, as we’ve broken the queryable ability at that point.