Entity Framework 中的Code First 中引入数据库函数

1,在项目中添加CodeFirstStoreFunctions包:

Install-Package EntityFramework.CodeFirstStoreFunctions

2,注册注册函数,FunctionsConvention第二个参数为函数定义所在的类

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ 
base.OnModelCreating(modelBuilder); 
//注册函数 
modelBuilder.Conventions.Add(new FunctionsConvention("dbo", this.GetType())); 
} 

3,定义函数对应的方法,要入数据中函数签名一致

[DbFunctionAttribute("CodeFirstDatabaseSchema", "getDistance")] 
public static double get_distance(double curLat, double curLng, double srcLat, double srcLng)
{
    throw new NotSupportedException();
}

 4,创建数据库函数

protected override void Seed(EFDbContextMobile context)
{
    context.Database.ExecuteSqlCommand(@"DROP FUNCTION IF EXISTS getDistance; CREATE FUNCTION getDistance(curLat DOUBLE, curLng DOUBLE, srcLat DOUBLE, srcLng DOUBLE) RETURNS DOUBLE BEGIN DECLARE dis DOUBLE; set dis = 6370996.81 * ACOS( COS(srcLat * PI() / 180) * COS(curLat * PI() / 180) * COS( srcLng * PI() / 180 - curLng * PI() / 180 ) + SIN(srcLat * PI() / 180) * SIN(curLat * PI() / 180)); RETURN dis; END"); 
}

 5,调用

复制代码
from moduleInfo in _shopInfoRepository.Entities select new ShopInfoBll() 
{ 
  PositionX = moduleInfo.PositionX,
  PositionY = moduleInfo.PositionX,         
  Distance= EFDbContextMobile.get_distance(40.09914694048, 116.42105702279, moduleInfo.PositionY, moduleInfo.PositionX)
}
        

你可能感兴趣的:(Entity Framework 中的Code First 中引入数据库函数)