GithubHelp home page GithubHelp logo

npgsql / efcore.pg Goto Github PK

View Code? Open in Web Editor NEW
1.5K 48.0 213.0 8.27 MB

Entity Framework Core provider for PostgreSQL

License: PostgreSQL License

C# 82.12% TSQL 17.88%
entity-framework npgsql postgres postgresql sql database entity-framework-core dotnet

efcore.pg's Introduction

Npgsql Entity Framework Core provider for PostgreSQL

stable next patch daily builds (vnext) build gitter

Npgsql.EntityFrameworkCore.PostgreSQL is the open source EF Core provider for PostgreSQL. It allows you to interact with PostgreSQL via the most widely-used .NET O/RM from Microsoft, and use familiar LINQ syntax to express queries. It's built on top of Npgsql.

The provider looks and feels just like any other Entity Framework Core provider. Here's a quick sample to get you started:

await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();

// Insert a Blog
ctx.Blogs.Add(new() { Name = "FooBlog" });
await ctx.SaveChangesAsync();

// Query all blogs who's name starts with F
var fBlogs = await ctx.Blogs.Where(b => b.Name.StartsWith("F")).ToListAsync();

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder.UseNpgsql(@"Host=myserver;Username=mylogin;Password=mypass;Database=mydatabase");
}

public class Blog
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Aside from providing general EF Core support for PostgreSQL, the provider also exposes some PostgreSQL-specific capabilities, allowing you to query JSON, array or range columns, as well as many other advanced features. For more information, see the the Npgsql site. For information about EF Core in general, see the EF Core website.

Related packages

efcore.pg's People

Contributors

adamsitnik avatar akilin avatar augustoproiete avatar austindrenski avatar brar avatar cornedbee avatar dependabot[bot] avatar ericstg avatar galadriel2143 avatar grzybsonssg avatar ins0mniaque avatar khellang avatar kinosang avatar marioprabowo avatar martingbrown avatar meyerovb avatar nathan-c avatar orace avatar ralmsdeveloper avatar roji avatar rus-art avatar rwasef1830 avatar scobei avatar slavanap avatar takerukoushirou avatar teyc avatar vonzshik avatar whatzgames avatar yohdeadfall avatar zpaks avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

efcore.pg's Issues

Can't scaffold database with expression indices

From @adopilot on December 5, 2015 19:57

Npqsql sometimes fail to Reverse engineering with exception which is unreadable to user.

I was trying to Scaffold database of Discourse forum.

In VS2015 console app created targeting .NETFramework,Version=v4.5.1 with EntityFramework7.Npgsql.Design.3.1.0-rc1-3 when try to Scaffold database using Package Manager Console by command like this

Scaffold-DbContext -provider EntityFramework7.Npgsql -connection "Port=5432;Server=xx.xx.xx.xx;Database=discourse;UserId=xx;Password=xx;"

user get generated exception like this

PM> Scaffold-DbContext -provider EntityFramework7.Npgsql -connection "Port=5432;Server=172.16.0.17;Database=discourse;UserId=;Password=;"
System.InvalidCastException: Column is null
   at Npgsql.BackendMessages.DataRowMessage.CheckNotNull()
   at Npgsql.NpgsqlDataReader.ReadColumnWithoutCache[T](Int32 ordinal)
   at Npgsql.NpgsqlDataReader.ReadColumn[T](Int32 ordinal)
   at Npgsql.NpgsqlDataReader.GetString(Int32 ordinal)
   at Microsoft.Data.Entity.Scaffolding.NpgsqlDatabaseModelFactory.GetColumns()
   at Microsoft.Data.Entity.Scaffolding.NpgsqlDatabaseModelFactory.Create(String connectionString, TableSelectionSet tableSelectionSet)
   at Microsoft.Data.Entity.Scaffolding.RelationalScaffoldingModelFactory.Create(String connectionString, TableSelectionSet tableSelectionSet)
   at Microsoft.Data.Entity.Scaffolding.NpgsqlScaffoldingModelFactory.Create(String connectionString, TableSelectionSet tableSelectionSet)
   at Microsoft.Data.Entity.Scaffolding.Internal.ReverseEngineeringGenerator.GetMetadataModel(ReverseEngineeringConfiguration configuration)
   at Microsoft.Data.Entity.Scaffolding.Internal.ReverseEngineeringGenerator.GenerateAsync(ReverseEngineeringConfiguration configuration, CancellationToken cancellationToken)
   at Microsoft.Data.Entity.Design.DatabaseOperations.ReverseEngineerAsync(String provider, String connectionString, String outputDir, String dbContextClassName, List`1 schemas, List`1 tables, Boolean useDataAnnotations, CancellationToken cancellationToken)
   at Microsoft.Data.Entity.Design.OperationExecutor.<ReverseEngineerImpl>d__19.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at Microsoft.Data.Entity.Design.OperationExecutor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
   at Microsoft.Data.Entity.Design.OperationExecutor.OperationBase.Execute(Action action)
Column is null

image

That is prryt unreadibile and hard to debug what is wrong with database

Here is gist dump of scema Discourse database I am trying to scaffold.

Copied from original issue: npgsql/npgsql#892

IServiceCollection does not contain a definition for AddNpgsql

I'm trying to use PostgreSQL for the first time and having a little trouble getting it to build without errors. To be sure I don't have conflicting packages, I made sure to update my project.json to RC2-*. Here's the final error that I can't seem to fix.

ERROR

Startup.cs(22,18): error CS1061: 'IServiceCollection' does not contain a definition for 'AddNpgsql' and no extension method 'AddNpgsql' accepting a first argument of type 'IServiceCollection' could be found (are you missing a using directive or an assembly reference?)

PARTIAL PROJECT.JSON

  "dependencies": {
    "AspNet.Security.OAuth.Introspection": "1.0.0-alpha1-final",
    "AspNet.Security.OAuth.Validation": "1.0.0-alpha1-final",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc.Formatters.Json": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Mvc.Cors": "1.0.0-rc2-final",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-final",

    "Microsoft.Extensions.Configuration.CommandLine": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0-rc2-final",
    "Microsoft.Extensions.Configuration.Json": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Console": "1.0.0-rc2-final",
    "Microsoft.Extensions.Logging.Debug": "1.0.0-rc2-final",

    "Microsoft.EntityFrameworkCore": "1.0.0-rc2-final",
    "Microsoft.EntityFrameworkCore.Commands": "1.0.0-rc2-*",
    "Microsoft.EntityFrameworkCore.Relational": "1.0.0-rc2-final",
    "Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0-*",
    "Microsoft.AspNetCore.Identity.EntityFrameworkCore": "1.0.0-rc2-final",

    "OpenIddict.Core": "1.0.0-*",
    "OpenIddict.EF": "1.0.0-*"
  },


  "frameworks": {
    "netcoreapp1.0": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.0.0-rc2-3002702"
        }
      },

      "imports": [
        "dnxcore50",
        "portable-net451+win8"
      ]
    }
  }

PARTIAL STARTUP.CS

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddEntityFramework()
                .AddNpgsql()
                .AddDbContext<DeadboltContext>(options =>
                    options.UseNpgsql("Host=localhost;Username=dev;Password=dev;Database=tesdb"));

            services.AddIdentity<tbl_ApplicationUser, tbl_ApplicationRole>()
                .AddEntityFrameworkStores<DeadboltContext>()
                .AddUserStore<CustomStore>()
                .AddDefaultTokenProviders()
                .AddOpenIddictCore<tbl_Application>
                    (conf => conf.UseEntityFramework());

            services.AddAuthorization(options => {
                options.AddPolicy("Default", builder => {
                    builder.RequireAuthenticatedUser();
                    builder.RequireActiveUser();
                });

                options.DefaultPolicy = options.GetPolicy("Default");
            });

            services.AddTransient<IEmailSender, AuthMessageSender>();
            services.AddTransient<IDatabaseInitializer, DatabaseInitializer>();
            services.AddTransient<IUtilityService, UtilityService>();
            services.AddScoped<ICommonRepository, CommonRepository>();
        }

Question: Entity Framework and json operators

Hi,
I'm trying to do a custom query:
Events.FromSql("SELECT * from events WHERE data @> '{\"$values\":[{\"Resource\": { \"$type\": \"myType\"}}]}'"); that selects Events based on some JSON data.

The query works just fine in raw SQL but when I try to use it with entity framework i get a exception: System.FormatException: Input string was not in a correct format.. I'd guess this is due to that the default parser do not know of @> ? It seems that the DefaultQuerySqlGenerator do not have any overrides to make entity framework understand this query.

Is it possible to do such query with the entity framework or do I need to resort to do query on the connection and custom deserialize my events.

This is rather a question, and I do not know how to tag it as such.

Cheers,
Mario

Stacktrace:

at System.Text.StringBuilder.AppendFormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.FormatHelper(IFormatProvider provider, String format, ParamsArray args)
   at System.String.Format(String format, Object[] args)
   at Microsoft.EntityFrameworkCore.Query.Sql.DefaultQuerySqlGenerator.GenerateFromSql(String sql, Expression arguments, IReadOnlyDictionary`2 parameters)
   at Microsoft.EntityFrameworkCore.Query.Sql.Internal.FromSqlNonComposedQuerySqlGenerator.Visit(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.Sql.DefaultQuerySqlGenerator.GenerateSql(IReadOnlyDictionary`2 parameterValues)
   at Microsoft.EntityFrameworkCore.Query.Internal.ShaperCommandContext.GetRelationalCommand(IReadOnlyDictionary`2 parameters)
...

Expose PostgreSQL JSON operators

From @roji on September 8, 2015 7:56

PostgreSQL supports a wide array of JSON operations. We may be able to translate at least some JSON operations in LINQ queries to PostgreSQL for backend processing - this would prevent the entire resultset from being pulled in to the client.

Explore the Newtonsoft.JSON API to see what can be done. We also probably don't want to take a dependency on Newtonsoft.JSON from the EF7 provider, so reference the JSON methods via reflection.

It may be a good idea to provide an opt-out for this in case there's trouble or client-side evaluation is preferred. At the query and model levels.

Copied from original issue: npgsql/npgsql#771

Non primary key integers are generated as "serial"

I have a model that looks like this:

public int Images_Large { get; set; }

And it has a default value defined in the OnModelCreating of a DbContext

entity.Property(e => e.Images_Large).HasDefaultValueSql("250");

The above code was generated by scaffolding an existing PostgresSQL database. I don't think it matters if you use HasDefaultValueSql("250") or HasDefaultValue(250).

When you try to update a PostgresSQL database, you get this error:

42601: multiple default values specified for column "Images_Large" of table "MyTable"

I generated a script using dotnet ef migrations script -o First.sql and loaded it in pgadmin3. The column was scaffolded as such:

"Images_Large" serial NOT NULL DEFAULT (250),

The "Images_Large" column is not the primary key of the database and therefore should not be mapped as serial. I changed the script to:

"Images_Large" integer NOT NULL DEFAULT (250),

And it's fixed.

This also happens to short and byte too.

Migrations script table column type always text without MaxLength

From @chrishaly on March 31, 2016 6:8

In my EF7 testing, a entity property was restricted with MaxLength

modelBuilder.Entity().Property(b => b.Url).HasMaxLength(128).IsRequired();

when use sql server, the migration script of the column has length

[Url] nvarchar(128) NOT NULL

but when us Npgsql the type is text without length, should be varchar(128).

"Url" text NOT NULL

code as follow:

namespace Ef7Test
{
    public class TestContext : DbContext
    {
        public DbSet<Person> Blog { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Person>().Property(b => b.Url).HasMaxLength(128).IsRequired();
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseNpgsql("server=localhost;user id=xx;password=xxx;database=Blog");
            //optionsBuilder.UseSqlServer("server=localhost;database=Blog");
            base.OnConfiguring(optionsBuilder);
        }
    }

    public class Person
    {
        public int PersonId { get; set; }
        public string Url { get; set; }
    }
}

migration script of Npgsql as follow:

CREATE TABLE "__EFMigrationsHistory" (
    "MigrationId" text NOT NULL,
    "ProductVersion" text NOT NULL,
    CONSTRAINT "PK_HistoryRow" PRIMARY KEY ("MigrationId")
);

CREATE TABLE "Person" (
    "PersonId" int4 NOT NULL,
    "Url" text NOT NULL, -- **type is text with out length, should be varchar(128)**
    CONSTRAINT "PK_Person" PRIMARY KEY ("PersonId")
);

INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion")
VALUES ('20160331053747_t1', '7.0.0-rc1-16348');

migration script of SqlServer as follow:

IF OBJECT_ID(N'__EFMigrationsHistory') IS NULL
    CREATE TABLE [__EFMigrationsHistory] (
        [MigrationId] nvarchar(150) NOT NULL,
        [ProductVersion] nvarchar(32) NOT NULL,
        CONSTRAINT [PK_HistoryRow] PRIMARY KEY ([MigrationId])
    );

GO

CREATE TABLE [Person] (
    [PersonId] int NOT NULL IDENTITY,
    [Url] nvarchar(128) NOT NULL,
    CONSTRAINT [PK_Person] PRIMARY KEY ([PersonId])
);

GO

INSERT INTO [__EFMigrationsHistory] ([MigrationId], [ProductVersion])
VALUES (N'20160331053747_t1', N'7.0.0-rc1-16348');

GO

Copied from original issue: npgsql/npgsql#1010

Using directives missing for PostgreSQL-specific types

From @adopilot on December 5, 2015 19:31

If you try to Scaffold-DbContext using EntityFramework7.Npgsql provider POCOS generated from tables with Network Address Types have wrong types in C#.

Here is my posgresql table

CREATE TABLE testInetTypes
(
  id integer NOT NULL, 
  ip_adrress inet, 
  ipv6 cidr,
  mac macaddr,
  CONSTRAINT idx_for_testInetTypes PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE doa
  OWNER TO postgres;
COMMENT ON COLUMN doa.id IS 'ado';
COMMENT ON COLUMN doa.ip_adrress IS 'This is ip addres INET type';

When npqsql Scaffold this table it creates POCO like this

   public partial class testinettypes
    {
        public int id { get; set; }
        public IPAddress ip_adrress { get; set; }
        public NpgsqlInet? ipv6 { get; set; }
        public PhysicalAddress mac { get; set; }
    }

C# .net do not recognized types IPAddress ,NpgsqlInet,PhysicalAddress

DbContext class created by npgsql looks like

protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseNpgsql(@"Port=5432;Server=xxxxxx;Database=ado;UserId=aa;Password='aa';");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<testinettypes>(entity =>
            {
                entity.Property(e => e.id).ValueGeneratedNever();

                entity.Property(e => e.ipv6).HasColumnType("cidr");
            });
        }

        public virtual DbSet<testinettypes> testinettypes { get; set; }

Copied from original issue: npgsql/npgsql#891

The type initializer for 'Npgsql.TypeHandlerRegistry' threw an exception.

From @Praecursor210 on November 19, 2015 20:22

I'm currently trying EntityFramework7 rc1-1. I have no problem on Windows but I have this exception on Linux with coreclr when I try to add a migration.

System.TypeInitializationException: The type initializer for 'Npgsql.TypeHandlerRegistry' threw an exception. ---> System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.Assembly.GetTypes()
   at Npgsql.TypeHandlerRegistry..cctor()
   --- End of inner exception stack trace ---
   at Microsoft.Data.Entity.Storage.Internal.NpgsqlTypeMapper..ctor()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CreateInstanceCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Data.Entity.Internal.DbContextServices.CreateModel()
   at Microsoft.Data.Entity.Internal.LazyRef`1.get_Value()
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.TransientCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.TransientCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Data.Entity.Design.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.Data.Entity.Commands.Program.Executor.<>c__DisplayClass6_0.<AddMigration>b__0()
   at Microsoft.Data.Entity.Commands.Program.Executor.Execute(Action action)
The type initializer for 'Npgsql.TypeHandlerRegistry' threw an exception.

Copied from original issue: npgsql/npgsql#876

Add option for sorting nulls first

PostgreSQL sorts NULL last in ORDER BY, but to best match C#/.NET behavior we should sort NULL first.

This would mean issuing ORDER BY ... NULLS FIRST in all queries, and also adding NULLS FIRST in index generation.

See dotnet/efcore#5723

Support for array types

From @eBerdnA on December 29, 2015 15:53

I just noticed that scaffolding a table which includes a column with datatype bytea[] can't be scaffolded. The following warning is generated.

Could not find type mapping for column 'public.File.md5Hash' with data type '_bytea'. Skipping column.
Unable to scaffold the index 'File_md5Hash_key' because one of the properties it contains could not be scaffolded.

I'm using a simple table like this.

CREATE TABLE "File"
(
  "FileId" serial NOT NULL,
  "Filename" character varying(255) NOT NULL,
  "md5Hash" bytea[] NOT NULL,
  CONSTRAINT "File_pkey" PRIMARY KEY ("FileId"),
  CONSTRAINT "File_md5Hash_key" UNIQUE ("md5Hash")
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "File"
  OWNER TO postgres;

Does this happen due to a limitation of the EntityFramework or due to an issue of npgsql?

Copied from original issue: npgsql/npgsql#926

Exception 'An operation is already in progress.' when lazy loading in a loop.

This throws 'An operation is already in progress.'. Maybe because somehow it 'forces' the provider to try to do MARS?

 foreach (var user in _userManager.Users)
            {
                List<string> userRoles = (await _userManager.GetRolesAsync(user)).ToList();
            }

Bringing the users into memory is the work around I used to get this working...

 foreach (var user in _userManager.Users.ToList())
            {
                List<string> userRoles = (await _userManager.GetRolesAsync(user)).ToList();
            }

Just thought I'd bring this example to your attention. Thanks for everything :)

npgsql does not respect default RC2 table naming conventions

From @crozone on June 7, 2016 4:22

As per this announcement , the default naming convention for tables in RC2 has been changed from using the entity class name as the default, to using the DbSet property name as the default.

Additionally, Migrations are now stored in ./Data/Migrations, instead of ./Migrations. this is an unrelated change.

When using the Npgsql adapter, the legacy RC1 naming conventions are still used.

Copied from original issue: npgsql/npgsql#1147

Unable to scaffold dbcontext (Database First)

In my project.json,

"dependencies": {
    "Microsoft.EntityFrameworkCore": "1.0.0-rc2-final",
    "Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0-rc2-release1",
    "Npgsql.EntityFrameworkCore.PostgreSQL.Design": "1.0.0-rc2-release1"
},
"tools": {
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview1-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  }

when i run at command prompt

dotnet ef dbcontext scaffold "<connection string>" Npgsql.EntityFrameworkCore.PostgreSQL.Design

I got this:

One or more errors occurred. (Unable to find expected assembly attribute named DesignTimeProviderServicesAttribute in provider assembly Npgsql.EntityFrameworkCore.PostgreSQL.Design. This attribute is required to identify the class which acts as the design-time service provider factory.)

Support transferring indices to a different schema

Migration operations such as RenameIndexOperation, RenameSequenceOperation don't work right now. PostgreSQL does support ALTER SEQUENCE x SET SCHEMA y, but the migration operations aren't currently structured properly (there's only an opaque newName).

Error when using Where with reference

Guys, I already opened this same issue at aspnet/EntityFramework rep, but I'm wondering whether the problem is with Npgsql or not. I'm trying to figure out why the following command doesn't work:

var availability = await 
    .Where(t => t.User.Id == user.Id && t.User.IsProfessional)
    .ToList();

I'm getting this error (Sorry about the size...):

An unhandled exception has occurred while executing the request
System.ArgumentException: Expression of type 'System.Func`2[Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[UPlatform.Models.UserAvailability,System.Collections.Generic.IAsyncEnumerable`1[UPlatform.Models.ApplicationUser]],UPlatform.Models.ApplicationUser],System.Nullable`1[System.Boolean]]' cannot be used for parameter of type 'System.Func`2[Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[UPlatform.Models.UserAvailability,System.Collections.Generic.IAsyncEnumerable`1[UPlatform.Models.ApplicationUser]],UPlatform.Models.ApplicationUser],System.Boolean]' of method 'System.Collections.Generic.IAsyncEnumerable`1[Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[UPlatform.Models.UserAvailability,System.Collections.Generic.IAsyncEnumerable`1[UPlatform.Models.ApplicationUser]],UPlatform.Models.ApplicationUser]] _Where[TransparentIdentifier`2](System.Collections.Generic.IAsyncEnumerable`1[Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[UPlatform.Models.UserAvailability,System.Collections.Generic.IAsyncEnumerable`1[UPlatform.Models.ApplicationUser]],UPlatform.Models.ApplicationUser]], System.Func`2[Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+TransparentIdentifier`2[UPlatform.Models.UserAvailability,System.Collections.Generic.IAsyncEnumerable`1[UPlatform.Models.ApplicationUser]],UPlatform.Models.ApplicationUser],System.Boolean])'

I thought it was because the table is empty and there is some problem when I'm trying to use the t.User property, but isn't. Wherever I try to access the User property reference, I get this error.

This strange behaviour starts when I updated to 1.0.0-rc2 versions.

If I remove the Where clausure, it works:

var availability = await context.UserAvailabilities.ToListAsync();

I already tried to replace ToListAsync() by ToList(), but I'm getting the same error.

Any help will be welcome. 👍

Thanks

Stop using "IS NOT DISTINCT FROM"

Performance issue due to the query generation on update.
It's using "IS NOT DISTINCT FROM" instead of "="
I don't think there's any reason to not use the "=" on not nullable field

Hstore issues

From @pbgodwin on December 21, 2015 0:29

I've built the following example application with a blank ASP.NET RC1 MVC template and EntityFramework7.Npgsql:

TestDbModel.cs:

public class TestDbModel
{

    public int Id { get; set; }

    public IDictionary<string, string> Data { get; set; } 

}

TestDbContext.cs:

public class TestDbContext : DbContext 
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<TestDbModel>()
            .Property(m => m.Id)
            .HasColumnType("int")
            .HasColumnName("id");

        modelBuilder.Entity<TestDbModel>()
            .Property(m => m.Data)
            .HasColumnType("hstore")
            .HasColumnName("data");

        base.OnModelCreating(modelBuilder);
    }
}

HomeController.cs

public class HomeController : Controller 
{
    public HomeController(TestDbContext dbContext)
    {
        dbContext.Database.EnsureCreated(); // throws exception
    }

    // ...
}

This results in the following being thrown:

System.InvalidOperationException was unhandled by user code
  HResult=-2146233079
  Message=The property 'Data' on entity type 'EfHstoreTestNpgsql.TestDbModel' has CLR type which is not supported by current provider and it has not been configured to use any supported column type.
  Source=EntityFramework.Core
  StackTrace:
       at Microsoft.Data.Entity.Metadata.Conventions.Internal.PropertyMappingValidationConvention.Apply(InternalModelBuilder modelBuilder) in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Metadata\Conventions\Internal\PropertyMappingValidationConvention.cs:line 26
       at Microsoft.Data.Entity.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder) in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Metadata\Conventions\Internal\ConventionDispatcher.cs:line 136
       at Microsoft.Data.Entity.Metadata.Internal.InternalModelBuilder.Validate() in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Metadata\Internal\InternalModelBuilder.cs:line 184
       at Microsoft.Data.Entity.ModelBuilder.Validate() in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\ModelBuilder.cs:line 44
       at Microsoft.Data.Entity.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator) in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Infrastructure\ModelSource.cs:line 79
       at Microsoft.Data.Entity.Infrastructure.ModelSource.<>c__DisplayClass8_0.<GetModel>b__0(Type k) in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Infrastructure\ModelSource.cs:line 51
       at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
       at Microsoft.Data.Entity.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator) in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Infrastructure\ModelSource.cs:line 51
       at Microsoft.Data.Entity.Internal.DbContextServices.CreateModel() in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Internal\DbContextServices.cs:line 57
       at Microsoft.Data.Entity.Internal.LazyRef`1.get_Value() in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Internal\LazyRef.cs:line 32
       at Microsoft.Data.Entity.Internal.DbContextServices.get_Model() in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Internal\DbContextServices.cs:line 70
       at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c.<AddEntityFramework>b__0_5(IServiceProvider p) in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\EntityFrameworkServiceCollectionExtensions.cs:line 113
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.<RealizeService>b__0(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
       at Microsoft.Data.Entity.Storage.DatabaseProviderServices.GetService[TService]() in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Storage\DatabaseProviderServices.cs:line 57
       at Microsoft.Data.Entity.Storage.Internal.NpgsqlDatabaseProviderServices.get_Creator()
       at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c.<AddEntityFramework>b__0_11(IServiceProvider p) in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\EntityFrameworkServiceCollectionExtensions.cs:line 119
       at Microsoft.Extensions.DependencyInjection.ServiceLookup.FactoryService.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass12_0.<RealizeService>b__0(ServiceProvider provider)
       at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
       at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
       at Microsoft.Data.Entity.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor) in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Infrastructure\AccessorExtensions.cs:line 44
       at Microsoft.Data.Entity.Infrastructure.DatabaseFacade.EnsureCreated() in C:\Dev\OSS\EntityFramework\src\EntityFramework.Core\Infrastructure\DatabaseFacade.cs:line 41
       at EfHstoreTestNpgsql.Controllers.HomeController..ctor(TestDbContext dbContext) in C:\Dev\Spikes\EfHstoreTestNpgsql\src\EfHstoreTestNpgsql\Controllers\HomeController.cs:line 13
       at lambda_method(Closure , IServiceProvider , Object[] )
       at Microsoft.AspNet.Mvc.Infrastructure.DefaultTypeActivatorCache.CreateInstance[TInstance](IServiceProvider serviceProvider, Type implementationType)
       at Microsoft.AspNet.Mvc.Controllers.DefaultControllerActivator.Create(ActionContext actionContext, Type controllerType)
       at Microsoft.AspNet.Mvc.Controllers.DefaultControllerFactory.CreateController(ActionContext actionContext)
       at Microsoft.AspNet.Mvc.Controllers.ControllerActionInvoker.CreateInstance()
       at Microsoft.AspNet.Mvc.Controllers.FilterActionInvoker.<InvokeAllActionFiltersAsync>d__52.MoveNext()
  InnerException: 

Copied from original issue: npgsql/npgsql#909

Deserialization order of jsonb

Hi, I wonder if there's a way of configuring postgres jsonb column to "preserve" the JSON payload ordering since Newtonsoft JSON.NET is extremely sensitive to find a "$type" param first...

I've got an example and a workaround on my question around JSON.NET on stackoverflow (http://stackoverflow.com/questions/37563603/deserialization-with-inheritance-newtonsoft-json-net-not-working-properly) but it hurts performance.

Is this solvable or is it a bug or by design.

Cheers,
Mario

Exception on dotnet ef database update

Hi,

i get an exception when i run the dotnet ef database update command

Project EntitiesEF (.NETCoreApp,Version=v1.0) was previously compiled. Skipping compilation.
System.Exception: Received unexpected backend message CopyInResponse. Please file a bug.
   at Npgsql.NpgsqlDataReader.NextResultInternal()
   at Npgsql.NpgsqlDataReader.NextResult()
   at Npgsql.NpgsqlCommand.Execute(CommandBehavior behavior)
   at Npgsql.NpgsqlCommand.ExecuteNonQueryInternal()
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, String executeMethod, IReadOnlyDictionary`2 parameterValues, Boolean openConnection, Boolean closeConnection)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues, Boolean manageConnection)
   at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommandExtensions.ExecuteNonQuery(IEnumerable`1 commands, IRelationalConnection connection)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Execute(IEnumerable`1 relationalCommands)
   at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
   at Microsoft.EntityFrameworkCore.Design.MigrationsOperations.UpdateDatabase(String targetMigration, String contextType)
   at Microsoft.EntityFrameworkCore.Tools.Cli.DatabaseUpdateCommand.<>c__DisplayClass0_0.<Configure>b__0()
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)
Received unexpected backend message CopyInResponse. Please file a bug.

I use the entityframeworkcore rc2 final, Npgsql.EntityFrameworkCore.PostgreSQL 1.0.0-rc2-release1 and npgsql 3.1.0.

OS debian 8.2 x64
Framework target netcoreapp1.0 because the net451 version of entityframeworkcore tools isn't unsupported on linux and macos.
Postgresql 9.4.6

tell me what other information i can give you.

Bad timeout on internal commands

Double of issue for Npgsql.EntityFrameworkCore.PostgreSQL
npgsql/npgsql#1100

in dependencies i use
"dependencies": {
"ExtCore.Data.Abstractions": "1.0.0-alpha8",
"ExtCore.Data.Models.Abstractions": "1.0.0-alpha8",
"ExtCore.Infrastructure": "1.0.0-alpha8",
"NETStandard.Library": "1.5.0-rc2-24027",
"Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0-rc2-release1"
},

I must add "Npgsql": "3.1.0" ?
or it working with out main "Npgsql" nuget?

Migration fails with HasPostgresExtension.

Hi,

I decided to use Guid as primary key. Added these lines to my db context OnModelCreating:

            builder.HasPostgresExtension("uuid-ossp");

            builder.Entity<ApplicationUser>(b =>
            {
                b.Property(u => u.Id).HasDefaultValueSql("newid()");
            });

            builder.Entity<Role>(b =>
            {
                b.Property(u => u.Id).HasDefaultValueSql("newid()");
            });

SELECT UUID_GENERATE_V4() => tested and it worked via efcore 7 successfully.

Dropped my database via ef command utility.
Deleted my migration folder content in solution.

When running dotnet ef migrations add Initial, I get this exception:

System.InvalidOperationException: The current CSharpMigrationOperationGenerator cannot scaffold operations of type 'Microsoft.EntityFrameworkCore.Migrations.Ope
rations.NpgsqlCreatePostgresExtensionOperation'. Configure your services to use one that can.
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationOperationGenerator.Generate(MigrationOperation operation, IndentedStringBuilder builder)
   at CallSite.Target(Closure , CallSite , CSharpMigrationOperationGenerator , Object , IndentedStringBuilder )
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationOperationGenerator.Generate(String builderName, IReadOnlyList`1 operations, IndentedStringB
uilder builder)
   at Microsoft.EntityFrameworkCore.Migrations.Design.CSharpMigrationsGenerator.GenerateMigration(String migrationNamespace, String migrationName, IReadOnlyList
`1 upOperations, IReadOnlyList`1 downOperations)
   at Microsoft.EntityFrameworkCore.Migrations.Design.MigrationsScaffolder.ScaffoldMigration(String migrationName, String rootNamespace, String subNamespace)
   at Microsoft.EntityFrameworkCore.Design.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsAddCommand.Execute(CommonOptions commonOptions, String name, String outputDir, String context, String st
artupProject, String environment, Action`1 reporter)
   at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsAddCommand.<>c__DisplayClass0_0.<Configure>b__0()
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)
The current CSharpMigrationOperationGenerator cannot scaffold operations of type 'Microsoft.EntityFrameworkCore.Migrations.Operations.NpgsqlCreatePostgresExtens
ionOperation'. Configure your services to use one that can.

I use efcore rc2 version and my nuget feedback:

    <add key="AspNetRelease" value="https://www.myget.org/F/aspnetrelease/api/v3/index.json" />
    <add key="NuGet.org" value="https://api.nuget.org/v3/index.json" />
    <add key="Npgsql" value="https://www.myget.org/F/npgsql-unstable/" />

Is there anybody else having same issue ?

Subsequent migrations after initial are not recognised by ApplicationDbContextModelSnapshot

From @NoCommonSense on November 21, 2015 19:52

Hey,

I'm having some trouble with my migrations following upgrading to RC1 final for EF7 and Npgsql. I'm finding that my initial migration is created properly, but any subsequent migrations are not modifying my ApplicationDbContextModelSnapshot.cs file.

In addition, the subsequent migrations appear to be removing all foreign key relationships added by the initial migration, and adding new ones in with Cascade on delete. I'm unsure whether Cascade on delete is now enabled by default in RC1 final, but I would expect this behavior to be added in my initial migration.

Please let me know if I can provide any more info or whether this question should be added to the EF7 repo instead.

Thanks!
Ian

Copied from original issue: npgsql/npgsql#880

Wrong Query Generation for Skip() and Take

From @chbach on November 18, 2015 20:36

Hi, I recently switched from SQLite to Postgres on EF7 and noticed the following bug. When using Skip() and Take() (LIMIT and OFFSET), some relational data would be missing in the resulting collection of objects.

I have two models, NewsEntry and Tag that are related in a many-to-many relation via the table Tagging. When I query all NewsEntries with Db.NewsEntries.Include(e => e.Taggings), everything works fine and the Tagging-relation is present and I can iterate over them. However, as soon as I start doing something like Db.NewsEntries.Include(e => e.Taggings).OrderByDescending(e => e.Date).Take(12) some of the Tagging-relations are missing.

I analyzed the generated queries and noticed the following thing. This is the generated query for the relation:

SELECT "t"."NewsEntryId", "t"."TagId"
FROM "Tagging" AS "t"
INNER JOIN (
    SELECT DISTINCT "e"."Date", "e"."Id"
    FROM "NewsEntry" AS "e"
    LIMIT 12
) AS "e" ON "t"."NewsEntryId" = "e"."Id"
ORDER BY "e"."Date" DESC, "e"."Id"

What seems odd to me is that the ORDER BY statement is at the very end and sorts the overall result, but should rather sort the NewsEntries, since we want to get the first 12 elements after sorting:

SELECT "t"."NewsEntryId", "t"."TagId"
FROM "Tagging" AS "t"
INNER JOIN (
    SELECT DISTINCT "e"."Date", "e"."Id"
    FROM "NewsEntry" AS "e"
    ORDER BY "e"."Date" DESC, "e"."Id"
    LIMIT 12
) AS "e" ON "t"."NewsEntryId" = "e"."Id"

You can compare the query with the query the SQLite adapter produces here: dotnet/efcore#3758

Can you please have a look into that?

Christoph

EDIT:

Moving the sorting to the front like Db.NewsEntries.OrderByDescending(e => e.Date).Include(e => e.Taggings) actually generates the right query. However there are still Taggings missing! I have no idea how that happens.

Copied from original issue: npgsql/npgsql#872

Lower case table and column names

Is it possible to have a config setting to lower case table and column names?

adding double-quotes is more annoying than having a table name like aspnetusers.

Properly reverse-engineer non-SERIAL sequences

From @angelcalvasp on January 24, 2016 23:57

I am having a problem with EF7 npgsql so I generated the Context with the design library and everything works fine so far, except that when I try to add a new item even tho it has a sequence generator it still takes in the value that is assigned on the object by default on the pk in this case 0, Ive tried to put -1 see if that helps but it wrote the -1 too XD.

entity.Property(e => e.IDFactura)
.HasDefaultValueSql("nextval('"Factura_FacturaID_seq"'::regclass)")
.ValueGeneratedNever();

for the serial

all Im doing is

db.Factura.Add(factura);
db.SaveChanges();

am I missing something?

Copied from original issue: npgsql/npgsql#959

NotMappedAttribute not works

From @kagamine on December 29, 2015 3:22

/cc @roji

In my model

    [NotMapped]
    public virtual ServiceStatus ServiceStatus
    {
        get
        {
            if (IsFuse && MobileStatus != ServiceStatus.未知)
                return (ServiceStatus)Math.Max((int)HardlinkStatus, (int)MobileStatus);
            else
                return HardlinkStatus;
        }
    }

and caught an exception

No backing field could be discovered for property 'ChinaTelecom.Grid.Models.House.ServiceStatus' and the property does not have a setter. Either use a backing field name that can be matched by convention, annotate the property with a backing field, or define a property setter.

To use x.Ignore(y => y.ServiceStatus) is ok, not mapped attribute is not works.

Copied from original issue: npgsql/npgsql#923

Allow users to specify PostgreSQL extensions

In some cases, we need to allow users to do stuff at database-creation time. Examples include:

  • Setting up extensions. Especially important for uuid but also hstore, postgis...
  • Specify the template database (#2)

Migration script produces invalid SQL

From @natemcmaster on September 11, 2015 23:52

Repro
Using these migration files: https://gist.github.com/natemcmaster/ad34901f065f8a76f656

Ran dnx ef migrations script -o output.sql

Output

https://gist.github.com/natemcmaster/ad34901f065f8a76f656#file-output-sql

IF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid=c.relnamespace WHERE c.relname='__MigrationHistory') THENCREATE TABLE "__MigrationHistory" (
    "MigrationId" text NOT NULL,
    "ProductVersion" text NOT NULL,
    CONSTRAINT "PK_HistoryRow" PRIMARY KEY ("MigrationId")
);
END IF
;

--- more ...

On execute, this SQL fails.

ERROR: syntax error at or near "IF"
LINE 1: END IF;

Setup
EntityFramework7.Npgsql 3.1.0-beta7-1
EntityFramework.Commands 7.0.0-beta7
Postgres 9.4.4

Copied from original issue: npgsql/npgsql#778

Package restore for RC2

Hi Roji,
I'm trying out the just-released-today RC2 bits and wanted to try the postgreSQL provider that you've been working on.

I have the following in my Nuget.config (copied from your test)
<add key="NpgsqlUnstable" value="https://www.myget.org/F/npgsql-unstable/api/v3/index.json" /
And in my project.json dependencies:
"Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0-*",

And this is my frameworks setup

 "frameworks": {
        "netcoreapp1.0": {
            "imports": [
                "dotnet5.6",
                "dnxcore50"
            ]
        }
    }

But,dotnet restore reports:
Unable to resolve 'Npgsql.EntityFrameworkCore.PostgreSQL (>= 1.0.0)' for 'DNXCore,Version=v5.0'.

Can you tell what I may have misaligned?

Thanks!

jsonb issues

From @IC3Q on October 29, 2015 15:26

I'm getting an error when I'm trying to save object with jsonb field in it.
Model looks like:

[Table("objects")]
public class MyObject
{
    [Column("id")]
    [Key]
    public int Id { get; set; }
    [Column("features")]
    public string Features { get; set; }
}

Database features column is type of jsonb.

Code called to save entity:

using(var context = new MyDatabaseContext())
{
    context.Objects.Add(new MyObject {Id = 1, Features = JsonConvert.SerializeObject(new MyObject { Id = 1})});
    context.SaveChanges();
}

And the exception:

Npgsql.NpgsqlException: 42804: column "features" is of type jsonb but expression is of type text

I'm using Npgsql.EntityFramework7 provider, version 3.1.0-beta8-2.
In Npgsql.EntityFramework6, ver. 3.0.3 everything worked smoothly.

Copied from original issue: npgsql/npgsql#845

Composite support

In npgsql/npgsql@a9401b1 I added composite type support, but since then EFCore changed things in a way that breaks it. It appears that the composite type is now picked up as a navigation property - this makes sense but find a way to make EFCore treat it as scalar?

Implement idempotent migration scripts

From @roji on September 8, 2015 18:6

EF7 can generate SQL scripts which bring your database to the latest migration state. There are two types for these scripts: idempotent (can be run over and over without errors) and non-idempotent. The Npgsql EF7 provider currently produces only non-idempotent scripts.

The problem lies with the EF7 API requiring a way to check if a table already exists, but PostgreSQL doesn't allow condition statements (i.e. IF something). This can be worked around by using PL/pgSQL (this is how the EnsureSchema migration is implemented).

See issue dotnet/efcore#3043.

Relevant tests are MigrationsNpgsqlTest.Can_generate_up_scripts and MigrationsNpgsqlTest.Can_generate_down_scripts. See methods in NpgsqlHistoryRepository which throw NotSupportedException.

Copied from original issue: npgsql/npgsql#775

Expose PostgreSQL XML functions

From @roji on September 8, 2015 8:4

PostgreSQL supports xpath matching, which we can expose to the user when corresponding methods are used in the LINQ query. This would prevent the entire resultset from being pulled in to the client.

It may be a good idea to provide an opt-out for this in case there's trouble or client-side evaluation is preferred. At the query and model levels.

Copied from original issue: npgsql/npgsql#773

Make tests run in parallel

For some reason there are severe timeout issues when running the test suite in parallel (the default). For now parallelism has been disabled (in AssemblyInfo.cs), investigate...

Error executing AddEntityFrameworkNpgsql

2016-06-08 16:14:15.8992 ERROR Could not load type 'Microsoft.Extensions.DependencyInjection.ServiceCollectionExtensions' from assembly 'Microsoft.Extensions.DependencyInjection.Abstractions, Version=1.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
2016-06-08 16:14:15.8992 ERROR at Microsoft.Extensions.DependencyInjection.NpgsqlEntityFrameworkServicesBuilderExtensions.AddEntityFrameworkNpgsql(IServiceCollection services)

Generate properties values on update

From @roji on September 6, 2015 22:16

EF7 allows defining a property as ValueGeneratedOnAddOrUpdate, but PostgreSQL doesn't have an easy built-in feature for this. This needs to be implemented with triggers - so define the function and trigger when the column is added (namespace?), drop it when it's removed...

Copied from original issue: npgsql/npgsql#759

Npgsql Code First Json Data Type Annotation

From @balaji8 on November 20, 2015 4:8

Hello,

I am trying to update a JSON column using Npgsql and having trouble with it. I am currently using: Microsoft.AspNet.Mvc: 6.0.0-beta8 and EntityFramework7.Npgsql: 3.1.0-beta8-2

I've tried both the System.ComponentModel.DataAnnotations.Schema attribute on the model:

[Column(TypeName = "json")] 

as well as the fluent api on the application context:

builder.Entity<Table>().Property(p => p.JsonColumn).HasColumnType("json");

It works just fine with Migrations and on Select queries. But when I try to update, it throws the following error: Npgsql.NpgsqlException: 42804: column "JsonColumn" is of type json but expression is of type text.

I am not sure how do I go about casting it back to Json. Or am I missing something?

Thanks,
Balaji

Copied from original issue: npgsql/npgsql#877

Copied from original issue: npgsql/EntityFramework6.Npgsql#29

Exception while calling SignInManager.PasswordSignInAsync with npgsql provider

From @ruicraveiro on September 17, 2015 0:9

Hi,

I am having an exception while using npgsql that is exclusive to this provider on EF7 (it doesn't happen with SQLite or SqlServer). The exception is the following:

error : [Microsoft.Data.Entity.Query.QueryContextFactory] An exception occurred in the database while iterating the results of a query.
System.InvalidOperationException: An operation is already in progress.
at Npgsql.NpgsqlConnector.StartUserAction (ConnectorState newState) [0x00000] in :0
at Npgsql.NpgsqlCommand.ExecuteDbDataReaderInternal (CommandBehavior behavior) [0x00000] in :0
at Npgsql.NpgsqlCommand.ExecuteDbDataReader (CommandBehavior behavior) [0x00000] in :0
at System.Data.Common.DbCommand.ExecuteReader () [0x00000] in :0
at (wrapper remoting-invoke-with-check) System.Data.Common.DbCommand:ExecuteReader ()
at Microsoft.Data.Entity.Query.QueryingEnumerable+Enumerator.MoveNext () [0x00000] in :0
at System.Linq.Enumerable+c__Iterator102[Microsoft.Data.Entity.Storage.ValueBuffer,Microsoft.Data.Entity.Query.QueryResultScope1[Microsoft.AspNet.Identity.EntityFramework.IdentityRole]].MoveNext () [0x00000] in :0
at System.Linq.Enumerable+c__Iterator122[Microsoft.Data.Entity.Query.QueryResultScope,Microsoft.Data.Entity.Query.QueryResultScope].MoveNext () [0x00000] in <filename unknown>:0 at System.Linq.Enumerable+<CreateSelectIterator>c__Iterator102[Microsoft.Data.Entity.Query.QueryResultScope,Microsoft.AspNet.Identity.EntityFramework.IdentityRole].MoveNext () [0x00000] in :0
at System.Linq.Enumerable+c__Iterator102[Microsoft.AspNet.Identity.EntityFramework.IdentityRole,Microsoft.AspNet.Identity.EntityFramework.IdentityRole].MoveNext () [0x00000] in <filename unknown>:0 at Microsoft.Data.Entity.Query.LinqOperatorProvider+ExceptionInterceptor1+EnumeratorExceptionInterceptor[Microsoft.AspNet.Identity.EntityFramework.IdentityRole].MoveNext () [0x00000] in :0
This is being thrown when I'm calling:

var result = await _signInManager.PasswordSignInAsync(model.Email,
model.Password,
model.RememberMe,
lockoutOnFailure: false);
where _signInManager is a Microsoft.AspNet.Identity.SignInManager.

This bug is only visible on an old and slow Linux machine I am testing the application on (I am using Elementary OS Freya). On my recent and fast Windows machine (with an SSD), the bug is not visible. I am perfectly capable of logging in and using the application. I am not sure if this has to do with the OS or if the much better performance of my Windows machine is hiding the problem.

The log is the following (showing both aspnet and npgsql):

info : [Microsoft.Framework.DependencyInjection.DataProtectionServices] User profile is available. Using '/home/rui/.local/share/ASP.NET/DataProtection-Keys' as key repository; keys will not be encrypted at rest.
Application started. Press Ctrl+C to shut down.
warning : [Microsoft.AspNet.Mvc.Core.ControllerActionInvoker] Authorization failed for the request at filter 'Microsoft.AspNet.Mvc.AuthorizeFilter'.
info : [Microsoft.Data.Entity.Storage.Database] Compiling query model: 'from IdentityRole x in value(Microsoft.Data.Entity.Query.EntityQueryable1[Microsoft.AspNet.Identity.EntityFramework.IdentityRole]) where [x].Name.Equals(__roleName_0) select [x] => FirstOrDefault()' info : [Microsoft.Data.Entity.Storage.Database] Optimized query model: 'from IdentityRole x in value(Microsoft.Data.Entity.Query.EntityQueryable1[Microsoft.AspNet.Identity.EntityFramework.IdentityRole]) where [x].Name.Equals(__roleName_0) select [x] => FirstOrDefault()'
info : [Microsoft.Data.Entity.Storage.Database] Tracking query sources: [x]
info : [Microsoft.Data.Entity.Storage.Database] TRACKED: True
(QueryContext prm0, QueryResultScope prm1) => () => IAsyncEnumerable TaskToSequence(
task: Task FirstOrDefault(
source: IAsyncEnumerable _Select(
source: IAsyncEnumerable _SelectMany(
source: IAsyncEnumerable _ToSequence(
element: prm1
)
,
selector: (QueryResultScope prm1) => IAsyncEnumerable<QueryResultScope> _ShapedQuery(
queryContext: prm0,
commandBuilder: SelectExpression:
SELECT TOP(1) "x"."Id", "x"."ConcurrencyStamp", "x"."Name", "x"."NormalizedName"
FROM "AspNetRoles" AS "x"
WHERE "x"."Name" = @__roleName_0
,
shaper: (ValueBuffer prm2) => QueryResultScope CreateEntity(
querySource: from IdentityRole x in value(EntityQueryable1[Microsoft.AspNet.Identity.EntityFramework.IdentityRole]), queryContext: prm0, parentQueryResultScope: prm1, valueBuffer: prm2, valueBufferOffset: 0, entityType: Microsoft.AspNet.Identity.EntityFramework.IdentityRole, queryStateManager: True, entityKeyFactory: SimpleNullSentinelEntityKeyFactory1,
keyProperties: List { IdentityRole.Id, },
materializer: (ValueBuffer prm3) =>
{
var var4
var4 = new IdentityRole()
var4.Id = (string) object prm3.get_Item(0)
var4.ConcurrencyStamp = (string) object prm3.get_Item(1)
var4.Name = (string) object prm3.get_Item(2)
var4.NormalizedName = (string) object prm3.get_Item(3)
var4
}
)
)
)
,
selector: (QueryResultScope prm1) => IdentityRole prm1._GetResult(
querySource: from IdentityRole x in value(EntityQueryable`1[Microsoft.AspNet.Identity.EntityFramework.IdentityRole])
)
)
,
cancellationToken: prm0.CancellationToken
)
)

DEBUG Opening connnection
TRACE Attempting to connect to 127.0.0.1
DEBUG Connected to 127.0.0.1:5433
DEBUG Authenticating...
TRACE Received AuthenticationRequest of type AuthenticationMD5Password
TRACE Received AuthenticationRequest of type AuthenticationOk
DEBUG ExecuteReader with CommandBehavior=Default
DEBUG [6122] ExecuteReader
TRACE [6122] Sending: [Query=SET statement_timeout = 0]
TRACE [6122] Sending: [Parse(Statement=,NumParams=0]
TRACE [6122] Sending: [Describe(Statement=)]
TRACE [6122] Sending: [Bind(Portal=,Statement=,NumParams=0]
TRACE [6122] Sending: [Execute(Portal=,MaxRows=0]
TRACE [6122] Sending: [Sync]
TRACE [6122] Array type '_aclitem' refers to unknown element with OID 1033, skipping
TRACE [6122] Array type '_oidvector' refers to unknown element with OID 30, skipping
TRACE [6122] Array type '_gtsvector' refers to unknown element with OID 3642, skipping
DEBUG ExecuteReader with CommandBehavior=Default
DEBUG [6122] ExecuteReader
TRACE [6122] Sending: [Query=SET statement_timeout = 30000]
TRACE [6122] Sending: [Parse(Statement=,NumParams=1]
TRACE [6122] Sending: [Describe(Statement=)]
TRACE [6122] Sending: [Bind(Portal=,Statement=,NumParams=1]
TRACE [6122] Sending: [Execute(Portal=,MaxRows=0]
TRACE [6122] Sending: [Sync]
DEBUG [6122] Closing connection
TRACE [6122] Really closing connection
info : [Microsoft.Data.Entity.Storage.Database] Compiling query model: 'from IdentityUserRole1 userrole in value(Microsoft.Data.Entity.Query.EntityQueryable1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole1[System.String]]) join ApplicationUser user in __p_0 on [userrole].UserId equals [user].Id where [userrole].RoleId.Equals(__role_Id_1) select [user]' info : [Microsoft.Data.Entity.Storage.Database] Optimized query model: 'from IdentityUserRole1 userrole in value(Microsoft.Data.Entity.Query.EntityQueryable1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole1[System.String]]) join ApplicationUser user in __p_0 on [userrole].UserId equals [user].Id where [userrole].RoleId.Equals(__role_Id_1) select [user]'
info : [Microsoft.Data.Entity.Storage.Database] Tracking query sources: [user]
info : [Microsoft.Data.Entity.Storage.Database] TRACKED: True
(QueryContext prm0, QueryResultScope prm1) => () => IAsyncEnumerable _Select(
source: IAsyncEnumerable _Join(
outer: IAsyncEnumerable _SelectMany(
source: IAsyncEnumerable _ToSequence(
element: prm1
)
,
selector: (QueryResultScope prm1) => IAsyncEnumerable<QueryResultScope> _ShapedQuery(
queryContext: prm0,
commandBuilder: SelectExpression:
SELECT "userrole"."UserId"
FROM "AspNetUserRoles" AS "userrole"
WHERE "userrole"."RoleId" = @__role_Id_1
,
shaper: (ValueBuffer prm2) => QueryResultScope CreateValueBuffer(
querySource: from IdentityUserRole1 userrole in value(EntityQueryable1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole1[System.String]]), queryContext: prm0, parentQueryResultScope: prm1, valueBuffer: prm2, valueBufferOffset: 0 ) ) ) , inner: IAsyncEnumerable<ApplicationUser> ToAsyncEnumerable( source: IEnumerable<ApplicationUser> GetParameterValue( queryContext: prm0, parameterName: __p_0 ) ) , outerKeySelector: (QueryResultScope prm1) => (string) object ValueBuffer prm1._GetResult( querySource: from IdentityUserRole1 userrole in value(EntityQueryable1[Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole1[System.String]])
)
.get_Item(0),
innerKeySelector: (ApplicationUser prm3) => prm3.Id,
resultSelector: (QueryResultScope prm1, ApplicationUser prm3) => QueryResultScope _Create(
querySource: join ApplicationUser user in __p_0 on [userrole].UserId equals [user].Id,
result: prm3,
parentScope: prm1
)
)
,
selector: (QueryResultScope prm1) => ApplicationUser prm1._GetResult(
querySource: join ApplicationUser user in __p_0 on [userrole].UserId equals [user].Id
)
)

info : [Microsoft.Data.Entity.Storage.Database] Compiling query model: 'value(Microsoft.Data.Entity.Query.EntityQueryable1[Identity.Model.ApplicationUser])' info : [Microsoft.Data.Entity.Storage.Database] Optimized query model: 'value(Microsoft.Data.Entity.Query.EntityQueryable1[Identity.Model.ApplicationUser])'
info : [Microsoft.Data.Entity.Storage.Database] Tracking query sources: [_0]
info : [Microsoft.Data.Entity.Storage.Database] TRACKED: True
(QueryContext prm0, QueryResultScope prm1) => () => IEnumerable _Select(
source: IEnumerable _SelectMany(
source: IEnumerable _ToSequence(
element: prm1
)
,
selector: (QueryResultScope prm1) => IEnumerable<QueryResultScope> _ShapedQuery(
queryContext: prm0,
commandBuilder: SelectExpression:
SELECT "a"."Id", "a"."AccessFailedCount", "a"."ConcurrencyStamp", "a"."Email", "a"."EmailConfirmed", "a"."LockoutEnabled", "a"."LockoutEnd", "a"."NormalizedEmail", "a"."NormalizedUserName", "a"."PasswordHash", "a"."PhoneNumber", "a"."PhoneNumberConfirmed", "a"."SecurityStamp", "a"."TwoFactorEnabled", "a"."UserName"
FROM "AspNetUsers" AS "a"
,
shaper: (ValueBuffer prm2) => QueryResultScope CreateEntity(
querySource: from ApplicationUser _0 in value(EntityQueryable1[Identity.Model.ApplicationUser]), queryContext: prm0, parentQueryResultScope: prm1, valueBuffer: prm2, valueBufferOffset: 0, entityType: Identity.Model.ApplicationUser, queryStateManager: True, entityKeyFactory: SimpleNullSentinelEntityKeyFactory1,
keyProperties: List { ApplicationUser.Id, },
materializer: (ValueBuffer prm3) =>
{
var var4
var4 = new ApplicationUser()
var4.Id = (string) object prm3.get_Item(0)
var4.AccessFailedCount = (int) object prm3.get_Item(1)
var4.ConcurrencyStamp = (string) object prm3.get_Item(2)
var4.Email = (string) object prm3.get_Item(3)
var4.EmailConfirmed = (bool) object prm3.get_Item(4)
var4.LockoutEnabled = (bool) object prm3.get_Item(5)
var4.LockoutEnd = (Nullable) object prm3.get_Item(6)
var4.NormalizedEmail = (string) object prm3.get_Item(7)
var4.NormalizedUserName = (string) object prm3.get_Item(8)
var4.PasswordHash = (string) object prm3.get_Item(9)
var4.PhoneNumber = (string) object prm3.get_Item(10)
var4.PhoneNumberConfirmed = (bool) object prm3.get_Item(11)
var4.SecurityStamp = (string) object prm3.get_Item(12)
var4.TwoFactorEnabled = (bool) object prm3.get_Item(13)
var4.UserName = (string) object prm3.get_Item(14)
var4
}
)
)
)
,
selector: (QueryResultScope prm1) => ApplicationUser prm1._GetResult(
querySource: from ApplicationUser _0 in value(EntityQueryable`1[Identity.Model.ApplicationUser])
)
)

DEBUG Opening connnection
DEBUG ExecuteReader with CommandBehavior=Default
DEBUG [6122] ExecuteReader
TRACE [6122] Sending: [Query=DISCARD ALL]
TRACE [6122] Sending: [Parse(Statement=,NumParams=1]
TRACE [6122] Sending: [Describe(Statement=)]
TRACE [6122] Sending: [Bind(Portal=,Statement=,NumParams=1]
TRACE [6122] Sending: [Execute(Portal=,MaxRows=0]
TRACE [6122] Sending: [Sync]
DEBUG ExecuteReader with CommandBehavior=Default
DEBUG [6122] ExecuteReader
error : [Microsoft.Data.Entity.Query.QueryContextFactory] An exception occurred in the database while iterating the results of a query.
System.InvalidOperationException: An operation is already in progress.
at Npgsql.NpgsqlConnector.StartUserAction (ConnectorState newState) [0x00000] in :0
at Npgsql.NpgsqlCommand.ExecuteDbDataReaderInternal (CommandBehavior behavior) [0x00000] in :0
at Npgsql.NpgsqlCommand.ExecuteDbDataReader (CommandBehavior behavior) [0x00000] in :0
at System.Data.Common.DbCommand.ExecuteReader () [0x00000] in :0
at (wrapper remoting-invoke-with-check) System.Data.Common.DbCommand:ExecuteReader ()
at Microsoft.Data.Entity.Query.QueryingEnumerable+Enumerator.MoveNext () [0x00000] in :0
at System.Linq.Enumerable+c__Iterator102[Microsoft.Data.Entity.Storage.ValueBuffer,Microsoft.Data.Entity.Query.QueryResultScope1[Identity.Model.ApplicationUser]].MoveNext () [0x00000] in :0
at System.Linq.Enumerable+c__Iterator122[Microsoft.Data.Entity.Query.QueryResultScope,Microsoft.Data.Entity.Query.QueryResultScope].MoveNext () [0x00000] in <filename unknown>:0 at System.Linq.Enumerable+<CreateSelectIterator>c__Iterator102[Microsoft.Data.Entity.Query.QueryResultScope,Identity.Model.ApplicationUser].MoveNext () [0x00000] in :0
at System.Linq.Enumerable+c__Iterator102[Identity.Model.ApplicationUser,Identity.Model.ApplicationUser].MoveNext () [0x00000] in <filename unknown>:0 at Microsoft.Data.Entity.Query.LinqOperatorProvider+ExceptionInterceptor1+EnumeratorExceptionInterceptor[Identity.Model.ApplicationUser].MoveNext () [0x00000] in :0

Copied from original issue: npgsql/npgsql#788

Support PostgreSQL enums

From @IC3Q on October 28, 2015 21:32

I'm using Npgsql.EntityFramework7 provider, version 3.1.0-beta8-2.

The problem is while trying to get entity from context which has some enum inside of it.

Postgres enum declaration:

CREATE TYPE public.my_enum AS
 ENUM ('value1','value2','value3');

Model:

[Table("my_table")]
public class Entity
{ 
        [Column("id")]
        [Key]
        public int Id { get; set; }
        [Column("type")]
        public MyEnum Type { get; set; }
}

Enum:

public enum MyEnum
{
    value1,
    value2,
    value3
}

Unfortunately, when you try to get something from database via entity framework it throws this error:

System.InvalidCastException: Can't cast database type my_enum to Int32

I've tried to register my enum in Npgsql (as it's pointed in npgsql documentation). With no effects.

Original question on stackoverflow: http://stackoverflow.com/questions/33394908/enum-handling-in-npgsql-and-entityframework7

Copied from original issue: npgsql/npgsql#842

Unable to resolve 'Npgsql.EntityFrameworkCore.PostgreSQL (>= 1.0.0)' for '.NETCoreApp,Version=v1.0'.

when i run the command ”dotnet restore", i got the error message:

Errors in c:\Users\xxx\Desktop\dotnet_test\project.json
    Unable to resolve 'Npgsql.EntityFrameworkCore.PostgreSQL (>= 1.0.0)' for '.NETCoreApp,Version=v1.0'.

dependencies in project.json:

  "dependencies": {
    "Microsoft.EntityFrameworkCore": "1.0.0-rc2-*",
    "Microsoft.EntityFrameworkCore.Relational": "1.0.0-rc2-*",
    "Microsoft.EntityFrameworkCore.Relational.Specification.Tests": "1.0.0-rc2-*",
    "Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0-*",
    "Npgsql": "3.1.0-*",
    "Microsoft.AspNetCore.Diagnostics": "1.0.0-*",
    "Microsoft.AspNetCore.Mvc": "1.0.0-*",
    "Microsoft.AspNetCore.Razor.Tools": {
      "type": "build",
      "version": "1.0.0-*"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-*",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0-*",
    "Microsoft.Extensions.Logging.Console": "1.0.0-*",
    "Microsoft.NETCore.App": {
      "type": "platform",
      "version": "1.0.0-*"
    }
  },

dotnet info

C:\Users\xxxx>dotnet --info
.NET Command Line Tools (1.0.0-rc2-002543)

Product Information:
 Version:     1.0.0-rc2-002543
 Commit Sha:  38d0c28a1e

Runtime Environment:
 OS Name:     Windows
 OS Version:  10.0.10586
 OS Platform: Windows
 RID:         win10-x64

Trying to get Npgsql working with mvc music store sample..

Hi,

I just try to run Npgsql with Ef Core using MVC. Music store sample is used in my tests.

I execute "dotnet ef update database" and it produces the following exception:

System.MissingMethodException: Method not found: 'Void Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator..ctor(Microsoft.EntityFrameworkCore.Metadata.IModel, Microsoft.EntityFrameworkCore.Storage.IRelationalConnection, Microsoft.EntityFrameworkCore.Migrations.IMigrationsModelDiffer, Microsoft.EntityFrameworkCore.Migrations.IMigrationsSqlGenerator)'.
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.ScopedCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetService[T](IServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.TransientCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ConstructorCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.TransientCallSite.Invoke(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.EntityFrameworkCore.Design.MigrationsOperations.AddMigration(String name, String outputDir, String contextType)
   at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsAddCommand.Execute(CommonOptions commonOptions, String name, String outputDir, String context, String startupProject, String environment, Action`1 reporter)
   at Microsoft.EntityFrameworkCore.Tools.Cli.MigrationsAddCommand.<>c__DisplayClass0_0.<Configure>b__0()
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at Microsoft.EntityFrameworkCore.Tools.Cli.Program.Main(String[] args)
Method not found: 'Void Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator..ctor(Microsoft.EntityFrameworkCore.Metadata.IModel, Microsoft.EntityFrameworkCore.Storage.IRelationalConnection, Microsoft.EntityFrameworkCore.Migrations.IMigrationsModelDiffer, Microsoft.EntityFrameworkCore.Migrations.IMigrationsSqlGenerator)'.

I am making the tests with linux. The sample works with Sqlite in Windows as expected.
I use dotnet version: 1.0.0-rc2-002611 (which I downloaded yesterday.)

Part of my project.json:

    "Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.0-*",
    "Npgsql.EntityFrameworkCore.PostgreSQL.Design": "1.0.0-*"

Part of my NuGet.config:

    <add key="Npgsql" value="https://www.myget.org/F/npgsql-unstable" />

Part of my Startup.cs:

                services.AddDbContext<MusicStoreContext>(options =>
                    options.UseNpgsql(Configuration[StoreConfig.ConnectionStringKey.Replace("__", ":")]));

Any ideas ? Thanks!

Expose PostgreSQL regex operators

From @roji on September 8, 2015 7:54

When a LINQ query contains a regex match (Regex.IsMatch), the EF7 provider can translate this to PostgreSQL regex matching, this way the matching happens in the backend without pulling the entire resultset to the client.

This was implemented and actually worked at some point in beta6 but APIs changed so it's now disabled.

The current implementation only maps the static Regex.IsMatch, we probably also want to do the instance-based matching methods.

It may be a good idea to provide an opt-out for this in case there's trouble or client-side evaluation is preferred. At the query and model levels.

Copied from original issue: npgsql/npgsql#770

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.