zoukankan      html  css  js  c++  java
  • 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) }
  • 相关阅读:
    mysql处理字符串
    关于git新建本地分支与远程分支关联问题
    phpexcel相关函数
    centos添加开机启动项目
    centos搭建NFS网络文件系统
    centos 查看版本(转)
    ubuntu搭建nfs网络文件系统
    linux 日常学习
    从现在开始强迫自己使用 Reflect
    正则小括号实践
  • 原文地址:https://www.cnblogs.com/ejiyuan/p/1720937.html
Copyright © 2011-2022 走看看