しばやん雑記

Azure とメイドさんが大好きなフリーランスのプログラマーのブログ

Entity Framework CTP5 でマッピング周りがわかりやすくなったよ

Code First Mapping Changes in CTP5 - ADO.NET Blog - Site Home - MSDN Blogs

知れば知るほど Code First を使いたくなってきますね。既にテストはいろいろ行ってますが、最初に Entity Framework が入った .NET 3.5 SP1 を思い出すと涙が出てきますね。

と、雑談はこのくらいにしておきます。Entity Framework CTP5 で Code First は Full data annotation support と Release Notes に書いてありましたが、具体的にはよくわかっていませんでした。でも大丈夫、解説記事が ADO.NET team Blog で公開されていました。最高ですね。

おさらいしておくと、CTP5 では以下の data annotation がサポートされています。

  • Full data annotation support
  • The full list of data annotations supported in CTP5 is;
    • KeyAttribute
    • StringLengthAttribute
    • MaxLengthAttribute
    • ConcurrencyCheckAttribute
    • RequiredAttribute
    • TimestampAttribute
    • ComplexTypeAttribute
    • ColumnAttribute
      • Placed on a property to specify the column name, ordinal & data type
    • TableAttribute
      • Placed on a class to specify the table name and schema
    • InversePropertyAttribute
      • Placed on a navigation property to specify the property that represents the other end of a relationship
    • ForeignKeyAttribute
      • Placed on a navigation property to specify the property that represents the foreign key of the relationship
    • DatabaseGeneratedAttribute
      • Placed on a property to specify how the database generates a value for the property (Identity, Computed or None)
    • NotMappedAttribute
      • Placed on a property or class to exclude it from the database
EF Feature CTP5 Released! - ADO.NET Blog - Site Home - MSDN Blogs

CTP5 で追加されたのは Column, Table, NotMapped ぐらいでしょうか。しかし、CTP4 では ModelBuilder を直接叩く必要があったカラム、テーブルの別名などをアノテーションで出来るようになりました。

プロパティ・フィールドにアノテーションで別名を付ける方法は

modelBuilder.Entity<Product>().MapSingleType(p => new { id = p.ProductId });

などとラムダと匿名型で指定するよりも簡潔ですし、モデルクラスを見るだけでマッピングが分かるので良いですね。*1

こう見ていると Fluent API が出る場面は全然ないように思いますが、継承などを定義する場合にはアノテーションだけでは不可能なので、今までのように ModelBuilder のメソッドを利用する必要があります。

ADO.NET team blog の記事には以下のパターン時の定義例が書いてあるので便利ですね。デザイナで定義するよりも圧倒的に簡単だと思います!

  • Table-per-hierarchy 継承
  • Table-per type 継承
  • Table-per concrete-type 継承

複雑なテーブルでもモデルをちゃんと作成、定義を行えば自動的に作ってくれるはずです!素敵、抱いて!!

そうそう、CTP4 まではエンティティの分割には対応していなかったと思うんですが、どなたか覚えていませんか?

*1:Code First では別名を付ける必要性はあまりないと思うので、主に DB ファースト用だと思います。