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

EF Core 2.2 spatial type can't be added to db migration

我正在尝试使用 EF 核心 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; }
}

如果我尝试用它创建迁移,我会收到以下错误:

The property 'Country.Border' is of an interface type ('IGeometry'). If it is a navigation property manually configure the relationship for this property by casting it to a mapped entity type, otherwise ignore the property using the NotMappedAttribute or 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

同样,如果我将其更改为几何类型,我会得到:

The property 'Geometry.UserData' could not be mapped, because it is of type 'object' which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in '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' does not contain a definition for 'UseNetTopologySuite' and no accessible extension method 'UseNetTopologySuite' accepting a first argument of type 'SqlServerDbContextOptionsBuilder' could be found (are you missing a using directive or an assembly reference?)

即使我安装了 nuget 包

  1. 安装相关的 NetTopologySuite 包,它 depends 在您使用的数据库上,例如您使用的是 SqlServer,所以您需要安装这个 NuGet 包:

Microsoft.EntityFrameworkCore.SqlServer.NetTopologySuite 2) Configure your database to use NetTopologySuite (the code to edit is normally in StartUp.ConfigureServices()). Just add , x => x.UseNetTopologySuite() inside the options.UseSqlServer brackets

看起来像这样:

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

我不必在文件中添加 using,因为我已经引用了,仅供参考,如果您需要它,它会是 Microsoft.EntityFrameworkCore

如果您在安装 NuGet 包后仍收到引用错误,请转至管理 NuGet 包并检查它是否在已安装列表中,以及它是否是清理并重建您的解决方案并重新启动 visual studio 它可能会有所帮助。