Entity Framework 6 Code First Custom Functions

前端 未结 1 401
一向
一向 2020-11-27 17:55

I\'m trying something similar to this:

How to use scalar-valued function with linq to entity?

However I\'m not using EDMX, but instead just DbContext and cod

相关标签:
1条回答
  • 2020-11-27 18:45

    You should be able to use a scalar SQL function in your Where criterias with CodeFirstStoreFunctions

    Assuming you want to map SQL function [dbo].[LatLongDistanceCalc], and according to the test suite:

    public class MyDataContext: DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
           //...
    
           modelBuilder.Conventions.Add(new FunctionsConvention("dbo", this.GetType()));
        }
    
        // "CodeFirstDatabaseSchema" is a convention mandatory schema name
        // "LatLongDistanceCalc" is the name of your function
    
        [DbFunction("CodeFirstDatabaseSchema", "LatLongDistanceCalc")]
        public static int LatLongDistanceCalc(int fromLat, int fromLong,
                                                           int toLat, int toLong)
        {
           // no need to provide an implementation
           throw new NotSupportedException();
        }
    }
    

    usage would then be:

    context.Locations
           .Where(e => MyDataContext.LatLongDistanceCalc(e.Lat, e.Long, lat, long) >= 10)
    
    0 讨论(0)
提交回复
热议问题