EF Core 2.2空间类型无法添加到数据库迁移中

时间:2019-02-20 18:15:18

标签: c# entity-framework spatial ef-core-2.2

我正在尝试使用EF core 2.2使用空间对象构建数据库,而在尝试创建数据库迁移时遇到了问题。使用https://docs.microsoft.com/en-us/ef/core/modeling/spatial,具体是:

class Country
{
    public int CountryID { get; set; }

    public string CountryName { get; set; }

    // Database includes both Polygon and MultiPolygon values
    public IGeometry Border { get; set; }
}

如果我尝试以此创建迁移,则会出现以下错误:

  

属性“ Country.Border”具有接口类型(“ IGeometry”)。   如果是导航属性,请手动配置以下关系   将此属性转换为映射的实体类型,否则忽略   使用NotMappedAttribute的属性或   “ OnModelCreating”中的“ EntityTypeBuilder.Ignore”。

类似地,如果我改为将其更改为Geometry类型,则会得到:

  

无法映射属性'Geometry.UserData',因为它具有   类型'object',它不是受支持的原始类型或有效类型   实体类型。显式映射此属性,或使用忽略它   '[NotMapped]'属性或通过使用'EntityTypeBuilder.Ignore'   “ OnModelCreating”。

我不提前知道我的对象是点还是线或多边形,因此它必须是通用的。我如何在我的结构中表示这一点?另外,我已经看到一些地方说我需要添加以下代码:

public class MyDBContextFactory : IDesignTimeDbContextFactory<MyDBContext>
    {

        public MyDBContext CreateDbContext(string[] args)
        {
            var builder = new DbContextOptionsBuilder<MyDBContext>();
            builder.UseSqlServer(cnnString, x => x.UseNetTopologySuite());
            return new MyDBContext(builder.Options);
        }
   }

但是我得到了错误:

  

'SqlServerDbContextOptionsBuilder'不包含以下定义   'UseNetTopologySuite',并且没有可访问的扩展方法   “ UseNetTopologySuite”接受类型的第一个参数   可以找到“ SqlServerDbContextOptionsBuilder”(您是否缺少   使用指令还是程序集引用?)

即使我已经安装了nuget程序包

1 个答案:

答案 0 :(得分:0)

是的,您确实需要UseNetTopologySuite,但它不会显示,因为您需要安装引用数据库服务器的软件包,在这种情况下,您将使用SqlServer

Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite

我只是这样设置

services.AddDbContext<ManagerContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),x=> x.UseNetTopologySuite()));

并且我没有出现错误,如果即使在安装了块状软件包之后也找不到参考,请转到“管理块状软件包”,并检查安装的软件包中是否存在该引用,以及它是否为Clean your solution,然后重新构建解决方案并重新启动visual工作室可能会有所帮助。