Calling a SQL User-defined function in a LINQ query

后端 未结 2 1230
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 06:53

I am having a hard time getting this to work. I am trying to do a radius search using the following Filter helper on an IQueryable. There are a set of other filters that get

2条回答
  •  春和景丽
    2020-12-01 07:34

    Ok, I think I understand the question - the gist of it is you want to be able to call a SQL UDF as part of your Linq to Entities query.

    This is if you're using database or model first:

    This article explains how to do it: http://msdn.microsoft.com/en-us/library/dd456847(VS.100).aspx

    To sum it up, you first need to edit your edmx file in an xml editor, in the edmx:StorageModels >> Schema section you need to specify a mapping to your sql udf, eg

    
        
    
    

    Then you need to create a static function somewhere with the EdmFunction attribute on it, something like this:

    public static class ModelDefinedFunctions
    {
        [EdmFunction("TestDBModel.Store", "SampleFunction")]
        public static int SampleFunction(int param)
        {
          throw new NotSupportedException("Direct calls are not supported.");
        }
    }
    

    This method will get mapped to the UDF at query time by entity framework. The first attribute argument is the store namespace - you can find this in your edmx xml file on the Schema element (look for Namespace). The second argument is the name of the udf.

    You can then call it something like this:

    var result = from s in context.UDFTests
                select new
                {
                    TestVal = ModelDefinedFunctions.SampleFunction(22)
                };
    

    Hope this helps.

提交回复
热议问题