NetCore-EFCore使用MySql.NetTopologySuite包支持空间类型查询附近的人

我的环境:

  • Abp vNext:5.1.2
  • EFCore:6.0
  • NetCore:6.0

一. 引用官方包

  • Pomelo.EntityFrameworkCore.MySql
  • Pomelo.EntityFrameworkCore.MySql.NetTopologySuite

二. 在{Obj}.EntityFrameworkCore层更改模块注入Options配置,添加UseNetTopologySuite
不使用abp的,在startup的ConfigService依赖注入的地方改options配置,同理。

public class {obj}EntityFrameworkCoreModule : AbpModule
{
	// ..
	public override void ConfigureServices(ServiceConfigurationContext context){
		 // ..
		 Configure<AbpDbContextOptions>(options =>
         {
            options.UseMySQL(mysqlOptions =>
            {
            	// 使用NetTopologySuite访问MySQL空间数据
                mysqlOptions.UseNetTopologySuite();
            }); 
         });
	}
}

三. 修改上下文工厂{obj}DbContextFactory内的CreateDbContext方法添加UseNetTopologySuite

public class {
    
    obj}DbContextFactory : IDesignTimeDbContextFactory<{
    
    obj}DbContext>{
    
    
 public {
    
    obj}DbContext CreateDbContext(string[] args)
    {
    
    
        {
    
    obj}EfCoreEntityExtensionMappings.Configure();

        var configuration = BuildConfiguration();
        
        var builder = new DbContextOptionsBuilder<{obj}DbContext>().UseMySql(
            configuration.GetConnectionString("Default"),
            MySqlServerVersion.LatestSupportedServerVersion,
            x => x.UseNetTopologySuite());
        
        return new {
    
    obj}DbContext(builder.Options);
    }
}

四. 在实体类中使用空间类型,例如Point位置

public class UserMaster {
    
    
	
	//..
	
	/// <summary>
    /// 用户位置
    /// </summary>
    public Point Location {
    
     get; set; }
}

五. 在使用linq查询时计算位置信息,例如:查找当前用户2千米范围内附近的人

// ..
NetTopologySuite.Geometries.Point currentPoint = new Point(39.930059,116.379413);
var query = await dbContext.Set<UserMaster>().FirstOrDefault(user.Location.Distance(currentPoint) <= 2)

PS:相关文档

猜你喜欢

转载自blog.csdn.net/csdn102347501/article/details/124596670