首先使用npgsql和EF6编写代码

时间:2017-03-25 00:50:48

标签: c# entity-framework-6 npgsql

我试图首先使用npgsql和Entity Framework创建一个简单的代码示例,但不断遇到错误。为什么?我已经阅读了所有我能阅读的内容,但没有找到解决办法!

凭据很好,我可以使用PgAdmin登录,而不是在我运行C#的同一台机器上发出问题。表未创建。用户是超级用户。

当我尝试.SaveChanges()时,我总是以UpdateException: An error occurred while updating the entries. See the inner exception for details.

的内部例外点击异常PostgresException: External component has thrown an exception.

我完全对此感到沮丧。我认为我的代码中最相关的部分是app.config:

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Npgsql" publicKeyToken="5d8b90d52f46fda7" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.2.2.0" newVersion="3.2.2.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <connectionStrings>
    <add name="contxt" connectionString="User ID=joe;Password=test;Host=192.168.xxx.xxx;Port=5432;Database=mydb" providerName="Npgsql" />
  </connectionStrings>
  <system.data>
    <DbProviderFactories>
<remove invariant="Npgsql" />
      <add name="Npgsql Data Provider" invariant="Npgsql" description="Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql" />
    </DbProviderFactories>
  </system.data>

实际代码不能简单:

class Program
{
    static void Main(string[] args)
    {
        using (var db = new Contxt())
        {
            var foo = new Foo { Name = "asdf" };
            db.Foos.Add(foo);

            db.SaveChanges();
        }
    }
}

public class Foo
{
    public Int64 Id { get; set; }
    public string Name { get; set; }
}

public class FooMapper : EntityTypeConfiguration<Foo>
{
    public FooMapper()
    {
        ToTable("Foos").HasKey<Int64>(x=>x.Id);
        Property(x => x.Name).HasMaxLength(255).IsVariableLength().IsRequired();
    }
}

public class Contxt : DbContext
{
    public DbSet<Foo> Foos { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.HasDefaultSchema("public");
        base.OnModelCreating(modelBuilder);
    }
}

0 个答案:

没有答案
相关问题