ちぐログ

メモ書きです

Entity Framework CoreでPostgreSQLを使ってみた2

Guidで怒られた

ModelにGuidを持つクラスを作って、context.Database.EnsureCreated();したら怒られました。

System.InvalidOperationException Property GroupId on type Test.Models.Group is a database-generated uuid, which requires the PostgreSQL uuid-ossp extension. Add .HasPostgresExtension("uuid-ossp") to your context's OnModelCreating.

ご丁寧に、OnModelCreatingでメソッドを実行してくれと書いてあるので実行してみます。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasPostgresExtension("uuid-ossp");
}

次のエラーはこれ。

Npgsql.PostgresException
42501: 拡張機能 "uuid-ossp" を作成する権限がありません

どうやらPostgreSQLで、拡張機能を追加する必要があるようです。

CREATE EXTENSION "uuid-ossp";postgresユーザで実行したら通りました。

エラーメッセージが親切で捗ります。

MVC

昔買ってあまり読んでいなかったけど、これを機に読みなおそうかと。
大枠はMVC5の頃とほとんど変わっていないという噂。

ASP.NET MVC5実践プログラミング

ASP.NET MVC5実践プログラミング

Entity Framework CoreでPostgreSQLを使ってみた

引き続き↓のページを見ながら。

Getting started with ASP.NET Core MVC and Entity Framework Core using Visual Studio — ASP.NET documentation

DBはPostgreSQL

最近何かとPostgreSQLというキーワードを聞くので、ローカルに立てたPostgreSQLでEntityFrameworkを使ってみたら予想外に簡単でした。 以下メモ。

project.jsonにNpgsql関連を追加

以下を追加。

"Npgsql": "3.1.8",
"Npgsql.EntityFrameworkCore.PostgreSQL": "1.0.2"

SqlServerのDIしている箇所をNpgsqlに変更

Getting started with ASP.NET Core MVC and Entity Framework Core using Visual Studio — ASP.NET documentation

を見るとStartup.csでSqlServerのDIが行われているので、これをNpgsqlに変更しました。

public void ConfigureServices(IServiceCollection services)  
{  
    services.AddDbContext<TestContext>(options => options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));  
}  

あとはcontext.Database.EnsureCreated(); したら、PostgreSQLにDBとテーブルが追加されました。