简体   繁体   中英

Custom extension method to simplify LINQ to SQL statement

I have a snippet of LINQ code that I need to use in a lot of queries

let catchmentId = Convert.ToInt32(
        phy.PhysicalProperty_binData.Substring(offset + 3, 1) +
        phy.PhysicalProperty_binData.Substring(offset + 2, 1) +
        phy.PhysicalProperty_binData.Substring(offset + 1, 1) +
        phy.PhysicalProperty_binData.Substring(offset, 1))

This translates well to SQL (and is more than performant for my specific needs), but makes my queries look ugly. Is there any way I can make this less verbose? Perhaps an extension method that returns an Expression> ? Note that I don't want to fetch the data to the client side (run it on the server as SQL), which makes things a little more complicated. For example:

let catchmentId = phy.PhysicalProperty_binData.AnExtensionMethodHere<int>(offset)

I tried writing an extension method that does this, but the provider simply ignores that call or throws an exception stating it doesn't know how to translate that call to SQL. Can we somehow extend the SQL generator to do this for us or provide it something in a way that will generate the same SQL?

Thanks in advance!

You can map custom SQL functions in your Entity model.

http://msdn.microsoft.com/en-us/library/dd456812(v=vs.103).aspx

The links on this page will show you how you can use custom attributes to tie your extension method to a user-defined function in your database.

Of course, that will mean that you need to create a user-defined function in SQL to do the same logic that your extension method wants to do.

Another option is to have your extension method produce an Expression , and use LINQKit to parse through the query tree, finding the call to .Compile() off of that expression, and inlining that expression in the query.

Wrong language (sorry) here it is in F# if people need.

let catchmentId =  
    // Curry in invariant components.
    let newSubstr end = 
        phy.PhysicalProperty_binData.Substring(offset + end, 1)
    Convert.ToInt32(
        newSubstr 3 +
        newSubstr 2 + 
        newSubstr 1 +
        newSubstr 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM