ハロの外部記憶インターフェイス

そろそろ覚える努力が必要かも…

Go LanguageでHello world

Goのインストール

ホームページからダウンロードして、書いている順で実行
Downloads - The Go Programming Language
今回はUbuntuに入れて見たんでLinuxのパターンで以下のコマンドを実行した。

sudo tar -C /usr/local -xzf go1.6.3.linux-amd64.tar.gz

後は.profileにパスを追加

export PATH=$PATH:/usr/local/go/bin

面白い注用コマンド

go fmt : ソースをGo専用フォーマットに変更してくれる。インデントなどがすべて自動で設定されるため便利
go run : ソースからコンパイルし実行する
go build : ビルドする
go install : ソースをビルドしGOPATH\binに実行ファイルを生成してくれる

Projectを作成してみる

GoのプロジェクトはGOPATHというプロジェクトルートフォルダ下に以下のようにフォルダを配置する
project_root
- bin : go installによって実行ファイルが配置される
- pkg : 依存パッケージのオブジェクトファイル
- src : ソースコードパッケージ毎にフォルダになる

※GOPATHは環境変数として、コンパイル前に設定する必要がる。

cd project_root
export GOPATH=`pwd`

Packageを作成してみる。
一つのパッケージは1つのフォルダ下で管理される
project_root
- src
- mypkg : mypkgのパッケージのソース
- main : mainパッケージのソース

/project_root/src/mypkg/mypkg.go

package mypkg
var Message string = "my message"

/project_root/src/main/main.go

package main
import (
"fmt"
"mypkg"
)

func main() {
fmt.Println(mypkg.Message)
}

実行してみる画面にmy messageが表示されればOK

cd $GOPATH\src\main
go run main.go

作ったソースのインストール

cd $GOPATH\src\main
go install main.go

binとpkgにファイルが生成されている。

go build -o execname source.go

「-o」オプションで実行ファイル名を指定が可能になる。

$ go  build -o hello hello.go

go build

実行フォルダに有るすべてのgoファイルをビルドする。


追記
go install は今はなくなり、以下の様に変更された模様

cd $GOPATH\src\main
go build

この場合、mainの実行ファイルが生成される。

./main
my message

サーバーエキスプローラーからPosgreSQLへのサーバー追加

dotConnect for PostgreSQLの導入

メニューから[ツール]-[拡張機能と更新プログラム]を選択
f:id:haronoid:20160806185347p:plain
dotconnectを検索しdotConnect for PostgreSqlをダウンロードし、インストールする。
f:id:haronoid:20160806185703p:plain
サーバーエキスプローラーからサーバー追加でPostgreSQLが選択可能になる。
f:id:haronoid:20160806190628p:plain
以降はDB接続情報を設定するだけで接続される。
f:id:haronoid:20160806191103p:plain
※テーブル名、カラム名が日本語の場合、詳細設定より、UnicodeをTrueにする必要がある。
f:id:haronoid:20160806191129p:plain

参照:
www21.atwiki.jp

SQL文をLogに出力する

EntityFrameworkが生成するSQL文をLogとして出力する。

以下のコードではDebug出力のみとしている。実際にSQLが発行された場合、デバック出力にSQL文が出力される。

    public class HomeController : Controller
    {
        MyDbContext _db;

        public OrderInventoryController()
        {
            _db = new Models.OrderContext();

            _db.Database.Log = sql => { Debug.Write(sql); };
        }
    }

PostgreSQLでTableAttributeのテーブル名がエラーになる

EntityモデルのTableAttributeにテーブル名を設定してもSqlがエラーになる。

まだ解決出来てないが備忘録として記載。

以下の様に実際のテーブル名をしてした。

[Table("Table1")]
public MyModel
{
}

DbContextではPropertyに以下の様に設定

public DbSet<MyModel> mymodels { get; set; }

実際取得してみるとエラーになる。

42P01: relation "dbo.Table1" does not exist

どうやら、MS SQLServer仕様の"dbo."が付くのがダメみたい。
これが出来ないとColumnAttrributeのカラム名しても使用できなくなる。

追記、DbContextのOnModelCreatingメソッドをオーバーライドでHasDefaultSchemaを指定して解決

public class MyContext : DbContext
{
  public MyContext() : base("MyDbSource")
  { }

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.HasDefaultSchema("public");
  }
}

参考:
mamelog.hatenablog.jp

PostgreSQLをEntityFrameworkで使う

Nugetを利用し、必要なパッケージをインストールする。

1.EntityFramework
2.Npgsql.EntityFrameworkCore.PostgreSQL
3.EntityFramework6.PostgreSql

※入れた記憶はないがNpgsqlは依存関係により、登録されていた(他にもいろいろ)

DbContextに直接ConnectionStringを設定する場合、

public class MyContext : DbContext
{
  public OrderContext() : base(new Npgsql.NpgsqlConnection("User ID=dbuser;Password=********;Host=localhost;Port=5432;Database=mydb;"),true)
  { }
}

Web.configにConnectionStringを設定する場合、

public class MyContext : DbContext
{
  public OrderContext() : base("DefaultDbSource")
  {}
}

Web.config

  <connectionStrings>
    <add name="DefaultDbSource" providerName="Npgsql" connectionString="User ID=dbuser;Password=********;Host=localhost;Port=5432;Database=mydb;" />
  </connectionStrings>
  <system.data>
    <DbProviderFactories>
      <add name="Npgsql Data Provider" invariant="Npgsql" description=".Net Framework Data Provider for Postgresql" type="Npgsql.NpgsqlFactory, Npgsql" />
    </DbProviderFactories>
  </system.data>

Entityモデルに複合キーを設定する

Entityモデルに複合キー設定

MyViewModel.cs

public class MyViewModel
{
[Key]
public string Clm1 { get; set; }
[Key]
public string Clm2 { get; set; }
public string Clm3 { get; set; }
}

実行してみると、取得時に以下のエラーになる。

型 'System.InvalidOperationException' の例外が EntityFramework.dll で発生しましたが、ユーザー コード内ではハンドルされませんでした

追加情報:Unable to determine composite primary key ordering for type 'myWeb.Models.MyViewModel'. Use the ColumnAttribute (see http://go.microsoft.com/fwlink/?LinkId=386388) or the HasKey method (see http://go.microsoft.com/fwlink/?LinkId=386387) to specify an order for composite primary keys.

原因は複合キーの順番が決まってないため

MyViewModel.csを以下の様に修正

public class MyViewModel
{
[Key]
[Column(Order =0)]
public string Clm1 { get; set; }
[Key]
[Column(Order =1)]
public string Clm2 { get; set; }
public string Clm3 { get; set; }
}

ColumnAttributeで順番を設定することで解決出来る

検索時も以下の様に使用可能になる。

context.MyViewModels.Find("first","second")