I have a method with several optional parameters that then updates the database using a LINQ query. I would like to update the record such that the optional fields are only saved if they were supplied in the method, otherwise the values should persist their old value. E.g.,
If I supply optional field "errorMessage" to my method, the database's corresponding record field should update with that value. If the method value is not supplied then I would like the database's record field to persist its existing content (filled or not). However, when using the ??
operator in my query to apply this logic I get the following error;
The parameterized query '(@p__linq__0 int,@p__update__0 nvarchar(198),@p__update__1 nvarc' expects the parameter '@p__update__1', which was not supplied.
I know enough LINQ to know that this basically means that it's having trouble converting the LINQ to SQL. Likewise, I could get around this by first loading the item, applying the method values to the retrieved object and then saving them but this turns a one-step operation into a 3 step operation. I'm hoping there's a concise elegant solution to this that I'm not aware of. Any ideas?
My code;
public void UpdateInvoiceExport(int quickBooksExportID, bool successful, string failureMessage = null,
int? failureRequestID = null, int? failureStatusCode = null,
string failureSeverity = null)
{
// only update certain details if the export was successful
DateTime? exportDateTime = null;
if (successful)
{
exportDateTime = DateTime.Now;
}
// update the export item
_context.QuickBooksExports.Update(item => item.QuickBooksExportID == quickBooksExportID,
qb => new QuickBooksExport
{
DateTimeExported = exportDateTime,
// the addition of the ?? operators here seems to cause the error
LastFailureMessage = failureMessage ?? qb.LastFailureMessage,
FailureRequestID = failureRequestID ?? qb.FailureRequestID,
FailureStatusCode = failureStatusCode ?? qb.FailureStatusCode,
FailureSeverity = failureSeverity ?? qb.FailureSeverity
});
_context.SaveChanges();
}
Update
a standard Linq2SQL function ? – Magnus May 20 '13 at 11:11Table
class – Magnus May 20 '13 at 15:20Update()
method is part ofEntityFramework.Extensions
and you can see the documentation here; efe.codeplex.com – DiskJunky May 20 '13 at 16:05