c# - Problem calling string manipulation method within linq-to-sql query -
i'm having frustrating issue trying use linq call string manipulation method. i've done lots of searching , have tried various method line noted 'fails' below work. throws exception.
some things i've tried:
a) creation of concatenated key in same query, didn't change anything
b) converting non-string fields strings (another whole can of works .tostring not working in linq. string.concat , string.format tried, work ok in cases not when try refer value later on)
c) using concat etc instead of '+' join things together.
as can see seems tolerant of appending strings non-strings, not when method invoked.
there lots of rows i'd prefer not convert data list/array etc, if that's option suggestions appreciated.
many thanks! - mark
var vouchers = v in db.vouchers select new { v.amount, v.due_date, v.invoice_date, v.po_cc, v.vendor_no_, v.invoice_no_, invoicenumeric = mfutil.stripnonnumeric(v.invoice_no_) }; var keyedvouchers = vv in vouchers select new { thekey = vv.vendor_no_ + "test", // works normal string thekey2 = vv.amount + "test", // works decimal thekey3 = vv.invoice_date + "test", // works date thekey4 = vv.invoicenumeric, // works thekey5 = vv.invoicenumeric + "test" // fails };
-- method strip chars ---
public static string stripnonnumeric(string str) { stringbuilder sb = new stringbuilder(); foreach (char c in str) { // append if withing acceptable boundaries // strip special chars: if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') | || (c >= 'a' && c <= 'z') | c == '.' || c == '_') // strip nonnumeric chars if (c >= '0' && c <= '9') { sb.append(c); } } return sb.tostring(); }
-- exception message--
system.invalidoperationexception unhandled user code message=could not translate expression 'table(voucher).select(v => new <>f__anonymoustype07(amount = v.amount, due_date = v.due_date, invoice_date = v.invoice_date, po_cc = v.po_cc, vendor_no_ = v.vendor_no_, invoice_no_ = v.invoice_no_, invoicenumeric = stripnonnumeric(v.invoice_no_))).select(vv => new <>f__anonymoustype1
5(thekey = (vv.vendor_no_ + "test"), thekey2 = (convert(vv.amount) + "test"), thekey3 = (convert(vv.invoice_date) + "test"), thekey4 = vv.invoicenumeric, thekey5 = (vv.invoicenumeric + "test")))' sql , not treat local expression.
it's because tries build sql query of expression , mfutil.stripnonnumeric
cannot translated sql.
try returning first , convert reult list , use second query convert it.
var vouchers_temp = v in db.vouchers select new { v.amount, v.due_date, v.invoice_date, v.po_cc, v.vendor_no_, v.invoice_no_ }; var vouchers = vouchers_temp.tolist().select( new { amount, due_date, invoice_date, po_cc, vendor_no_, invoice_no_, invoicenumeric = mfutil.stripnonnumeric(invoice_no_) });
Comments
Post a Comment