C# 实体框架:关键字不支持:'port'

17

你好,我有多个与CodeFirst Entity Framework连接的项目,除了一个顽固的项目外,所有项目都能成功连接到特定的DB。

我得到的错误是:Keyword not supported: 'port'

我查看了无数的stackoverflow问题、mysql论坛、entity framework论坛等,包括:

MappingException Edm.String not compatible with SqlServer.varbinary

Keyword not supported in MySQL's connection string

Keyword not supported: 'metadata' + MySQL

我的连接字符串如下:

server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123

我的db.cs文件如下:

public partial class MyDB : DbContext
{
    public MyDB ()
        : base("server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123")
    {
        Logger.Trace("test123");
    }

    public virtual DbSet<MyItem> MyItems { 
get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MyItem>()
            .Property(e => e.Content)
            .IsUnicode(false);
    }
}

当我从连接字符串中移除 port:3306,我得到了这个:

System.Data.Entity.Core.MappingException: Schema specified is not valid. Errors: 
(8,12) : error 2019: Member Mapping specified is not valid. The type 'Edm.DateTime[Nullable=False,DefaultValue=,Precision=]' of member 'Time' in type 'something.Model.MyItem' is not compatible with 'SqlServer.timestamp[Nullable=False,DefaultValue=,MaxLength=8,FixedLength=True,StoreGeneratedPattern=Identity]' of member 'time' in type 'CodeFirstDatabaseSchema.MyItem'.
   at System.Data.Entity.Core.Mapping.StorageMappingItemCollection.Init(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable`1 xmlReaders, IList`1 filePaths, Boolean throwOnError)
   at System.Data.Entity.Core.Mapping.StorageMappingItemCollection..ctor(EdmItemCollection edmCollection, StoreItemCollection storeCollection, IEnumerable`1 xmlReaders)
   at System.Data.Entity.ModelConfiguration.Edm.DbDatabaseMappingExtensions.ToStorageMappingItemCollection(DbDatabaseMapping databaseMapping, EdmItemCollection itemCollection, StoreItemCollection storeItemCollection)
   at System.Data.Entity.ModelConfiguration.Edm.DbDatabaseMappingExtensions.ToMetadataWorkspace(DbDatabaseMapping databaseMapping)
   at System.Data.Entity.Internal.CodeFirstCachedMetadataWorkspace..ctor(DbDatabaseMapping databaseMapping)
   at System.Data.Entity.Infrastructure.DbCompiledModel..ctor(DbModel model)
   at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
   at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
   at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
   at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
   at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
   at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
   at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
   at System.Data.Entity.DbSet`1.Add(TEntity entity)
   at MyFunction(Int32 userId, String id, String type, String contentJsonString) in 

我正在使用MySQL连接器而不是SQL Server...

我和我的团队完全被这个问题难住了。

编辑:这是我的Web.Config文件

    <?xml version="1.0"?>
    <configuration>
      <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
      </configSections>
      <appSettings file="config-sources\app-settings.config"/>
      <system.web>
        <compilation debug="true" targetFramework="4.5.2">
          <assemblies>
            <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
          </assemblies>
        </compilation>
        <httpRuntime targetFramework="4.5.1"/>
      </system.web>
      <connectionStrings configSource="config-sources\ef-connection-strings.config"/>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="MySql.Data" publicKeyToken="C5687FC88969C44D" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-6.8.3.0" newVersion="6.8.3.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-3.3.0.0" newVersion="3.3.0.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-4.2.29.0" newVersion="4.2.29.0"/>
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
        <providers>
          <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices,          MySql.Data.Entity.EF6" />
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
      <system.webServer>
        <handlers>
          <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
          <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="POST,HEAD,GET" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
        </handlers>
        <security>
          <requestFiltering>
            <verbs>
              <add verb="POST" allowed="true"/>
            </verbs>
          </requestFiltering>
        </security>
        <defaultDocument>
          <files>
            <add value="webhook.ashx"/>
          </files>
        </defaultDocument>
      </system.webServer>
    </configuration> 

你的端口号不是问题所在。虽然不能像那样指定它,但除非你更改了Mysql默认端口,否则你不必这样做。 - NormTheThird
也许这就是你遇到的同样问题 => https://dev59.com/N2ct5IYBdhLWcg3wULzo - NormTheThird
你能发布配置文件的相关部分吗?“port”异常表示EF正在尝试连接到Sql Server。 - Ivan Stoev
@NormTheThird,我已经研究过了,即使将我的DateTime更改为TimeSpan,我仍然会遇到相同的错误。 真正奇怪的是,这个错误是关于SqlServer的,而我既没有使用它,也不想使用它! - Alon Bukai
6个回答

16
使用的基础DbContext的参数constructor被称为nameOrConnectionString。因此,它支持配置文件中连接字符串的名称,或者像您的情况一样,实际的连接字符串。
后一种方法的问题在于它不允许指定提供程序名称,而前者可以从配置中获取;在这种情况下,EF将使用在defaultConnectionFactory配置元素中指定的提供程序名称,而在您的情况下是System.Data.Entity.Infrastructure.SqlConnectionFactory
换句话说 - Sql Server;因此出现了port不支持的异常。
修复此问题有几种方法:
  1. 更改defaultConnectionFactory配置
<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, 
MySql.Data.Entity.EF6"></defaultConnectionFactory>

使用命名配置连接字符串,并明确指定提供程序:
<connectionStrings>
  <add name="MyDB" providerName="MySql.Data.MySqlClient" 
     connectionString="server=myservername;port=3306;
     uid=myaccount;database=mydb;pwd=mypwd123" />
</connectionStrings>

将构造函数更改为:
public MyDB()
{
    // ...
}

或者,如果名称与您的DbContext派生类的名称不同:
public MyDB() : base(connection_string_name)
{
    // ...
}

使用DbConfigurationTypeAttribute
public class MyDB : DbContext 
{
    // ...
}

非常感谢!虽然我想使用选项(C),但最终我使用了选项(A)。我无法从任何地方导入 MySql.Data.Entity,可能需要更新我的 MySqlConnector 版本。 - Alon Bukai
我应该把(A)解决方案放在哪里?在csproj文件中吗? - Haikal Nashuha
@HaikalNashuha(A)是指App.config(或Web.config)文件。 - Ivan Stoev

9

在开发Core 2的Web应用程序时,我遇到了这个问题。我需要在配置应用程序的Startup.cs文件中将默认数据库连接从SqlServer更改为MySql。

enter image description here


8
在使用ASP.net core和数据库时,可能会遇到类似于上面列出的错误。ASP.net core的默认数据库提供程序是SQL Server,但是如果您使用不同的提供程序,例如PostgreSQL,并且没有正确编写或配置startup.cs中的DBContext代码,则会出现错误。
例如-以下代码旨在连接到PostgresSQL,然后会导致错误ArgumentException: Keyword not supported: 'port'.
public void ConfigureServices(IServiceCollection services)
{
   services.AddMvc();
   var connection = @"Server=localhost;Port=5432;Database=NewDB;User Id=xxxxx;Password=cr@aaaa;";
   services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));

    // ...

}

问题原因是用户在配置PostgreSQL字符串后,尝试连接到PostgreSQL但未更改默认选项UseSqlServer。

要解决此问题,请更改选项


options.UseSqlServer(connection)) -> options.UseNpgsql(connection))



2

我通过使用MySql Connector 8.0.x并遵循此链接上的说明,最终解决了问题:https://davidsekar.com/asp-net/mysql-error-the-provider-did-not-return-a-providermanifesttoken

具体来说:

  1. 安装 MySql.Data.EntityFramework。不要安装 Install MySql.Data.Entity!

  2. 按照以下方式配置 web.config / app.config:

    2.1. 将 <entityFramework> 标签更改为 <entityFramework codeConfigurationType="MySql.Data.EntityFramework.MySqlEFConfiguration, MySql.Data.EntityFramework">

    2.2. 添加/更改提供程序。它必须是:<provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.EntityFramework" />

    2.3. 连接字符串现在可以是 server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123

  3. 打开 DbContext 的配置类(如果存在),并将以下代码放入其构造函数中:SetSqlGenerator("MySql.Data.MySqlClient" new MySql.Data.EntityFramework.MySqlMigrationSqlGenerator());


0
在我的情况下,使用显式端口的连接字符串必须用逗号,分隔。
例如:Data Source=123.45.123.45,1433;...

-2
有时候最简单的事情会出错。我的问题是复制粘贴时错过了连接字符串开头的 "Server="。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接