首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >C#实体框架:关键字不支持:‘端口’

C#实体框架:关键字不支持:‘端口’
EN

Stack Overflow用户
提问于 2017-07-20 14:09:08
回答 6查看 31.5K关注 0票数 15

你好,我有多个项目连接到一个特定的DB,即CodeFirst实体框架。

除了一个顽固的项目外,所有项目都能成功地连接起来。

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

我查看了无数的堆栈溢出问题、mysql论坛、实体框架论坛等,包括:

MappingException Edm.String与SqlServer.varbinary不兼容

在MySQL的连接字符串中不支持关键字

关键字不受支持:“元数据”+ MySQL

我的连接字符串看起来像:server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123

我的db.cs文件看起来如下:

代码语言:javascript
运行
复制
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时,我得到如下信息:

代码语言:javascript
运行
复制
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连接器,而不是Server。

我和我的团队其他成员一样,都被这件事搞糊涂了。

编辑:这是我的Web.Config

代码语言:javascript
运行
复制
    <?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> 
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2017-07-20 17:04:11

使用的基DbContext 构造函数的参数称为nameOrConnectionString。因此,它支持配置文件中的连接字符串的名称,或者类似于实际的连接字符串。

后者的问题是,它不允许指定提供程序名称,就像前者来自配置一样,在这种情况下,EF使用defaultConnectionFactory配置元素中指定的名称,换句话说,在您的示例中是System.Data.Entity.Infrastructure.SqlConnectionFactory - Server,因此port不支持异常。

有几种方法可以解决这个问题。

(A)更改defaultConnectionFactory配置:

代码语言:javascript
运行
复制
<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6"></defaultConnectionFactory>

(B)使用命名配置连接字符串并显式指定提供程序:

代码语言:javascript
运行
复制
<connectionStrings>
    <add name="MyDB" providerName="MySql.Data.MySqlClient" connectionString="server=myservername;port=3306;uid=myaccount;database=mydb;pwd=mypwd123" />
</connectionStrings>

并将构造函数更改为

代码语言:javascript
运行
复制
public MyDB()
{
    // ...
}

或者如果名称与您的DbContext派生类名不同:

代码语言:javascript
运行
复制
public MyDB() : base(connection_string_name)
{
    // ...
}

(C)使用DbConfigurationTypeAttribute

代码语言:javascript
运行
复制
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class MyDB : DbContext
{
    // ...
}
票数 15
EN

Stack Overflow用户

发布于 2018-04-11 11:07:47

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

票数 9
EN

Stack Overflow用户

发布于 2018-03-14 04:04:24

类似于上面列出的错误是在使用ASP.net内核和数据库时出现的。具有ASP.net核心的默认数据库提供程序是Server,但如果您使用的是不同的提供程序(例如,PostgreSQL ),并且没有在startup.cs中正确地编写或配置DBContext代码

例如,编写以下代码的目的是要连接到PostgresSQL,然后它将导致错误ArgumentException:关键字不受支持:'port'.

代码语言:javascript
运行
复制
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(连接)) -> options.UseNpgsql(连接))

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45217166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档