c# - How do I calculate a checksum on all columns in a row using LINQ and Entity Framework? -


the query trying execute similar this:

var checksum = in db.items     i.id == id     select sqlfunctions.checksum("*"); 

however, returns checksum value of string "*" rather evaluating wildcard. there way calculate checksum of columns instead?

update:

var checksum = db.database.sqlquery<int?>("select checksum(*) [catalog].[item] id = @p0", id); 

this gives me result want seems dirty. there way without inline sql?

this can done sqlfunctions class. class allows linq-to-entities code include methods converted sql.

first of in current edit: using inline sql not 'dirty' , totally fine in (if not all) cases. orms don't provide everything, if there isn't object-column mapping exists. however, since you're using entity framework might aquanted sqlfunctions static methods.

in case there lot of overloads performing checksum, must of same type. since didn't post types columns or how many have, don't want recommend wrong overload in example use.

here options:

sqlfunctions.checksum():

  • bool?
  • char[]
  • datetime?
  • datetimeoffset?
  • decimal?
  • double?
  • guid?
  • timespan?
  • string

all of above have overloads allow 3 parameters (of same type).

sqlfunctions.aggregatechecksum():

  • ienumerable<int>
  • ienumerable<int?>

if take @ documentation these functions you'll see parameters you're passing values, not column names. should using them inside of select() clause. why when passed "*" operation checksummed string containing single asterisk instead of columns. also, keep in mind these functions cannot called directly, , must used within linq-to-entities query.

let's assume columns named "itemname" & "description" both strings, , want id, int:

var checksum = db.items.where(i => i.id == id)                        .select(i => sqlfunctions.checksum(i.id.tostring(), i.itemname, i.description)); 

unfortunately, see in above example had cast our int string. there no overloads allow different typed parameters computing checksum, nor there options allow more 3 parameters in checksum function; however, mentioned above need inline sql command , ok.


Popular posts from this blog