クライアントインターフェイスガイド > TDV用TIBCO ADO .NET 2020データプロバイダー > ADO.NET(Entity Framework)の使用 > コードファーストアプローチ
 
コードファーストアプローチ
プロバイダーからモデルをイントロスペクトする代わりに、モデルクラスを手書きすることもできます。これは、Entity Frameworkへのコードファーストのアプローチであり、アプリケーションで使用する正確なデータモデルをより細かく制御できます。
EntityFrameworkをインストールする
Install Entity Framework or add references to the required assemblies for your chosen version of Entity Framework. See Using EF 6 for using Entity Framework 6. See Installed Assemblies for more information about all assemblies shipped with the provider.
プロバイダーを登録する
接続文字列をApp.ConfigまたはWeb.configに追加します。 connectionStringsノードは、多くの場合、ルート構成ノードのconfigSectionノードのすぐ下にあります。
 
<configuration>
...
<connectionStrings>
<add name="CompositeContext" connectionString="Host=myHost;Domain=myDomain;DataSource=myDataSource;User=myUser;Password=myPassword" providerName="System.Data.CompositeClient" />
</connectionStrings>
...
</configuration>
コンテキストクラスを作成する
CompositeContextクラスを作成することから始めます。これは、DbContextを拡張し、データソースのテーブルを表すDbSetプロパティを公開するベースオブジェクトです。次に、OnModelCreatingメソッドをオーバーライドして、DbContextクラスのデフォルト機能の一部をオーバーライドします。これらのプロパティの説明は、以下のコードにあります。
 
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration.Conventions;
class CompositeContext : DbContext {
public CompositeContext() { }
public DbSet<Products> Products { set; get; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// To remove the requests to the Migration History table
Database.SetInitializer<CompositeContext>(null);
// To remove the plural names
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
//For versions of EF before 6.0, uncomment the following line to remove calls to EdmTable, a metadata table
//modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
}
}
テーブルモデルを作成する
最後に、コンテキストクラスのDbSetプロパティで定義された各テーブルのクラスを定義します。テーブルクラスには、そのテーブルの各フィールドに対応するプロパティのリストが必要です。テーブルクラスの各プロパティの属性を構成するには、対応するマップクラスを定義する必要があります。
 
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel.DataAnnotations.Schema; //EF 6 and later
//using System.ComponentModel.DataAnnotations //For versions of EF before 6
[System.ComponentModel.DataAnnotations.Schema.Table("Products")]
public class Products {
[System.ComponentModel.DataAnnotations.Key]
public System.String Id { get; set; }
public System.String ProductName { get; set; }
}
コードでLINQコマンドを実行する
これで、コードでLINQの使用を開始する準備が整いました。必ずファイルで「usingSystem.Linq」を宣言してください。
 
CompositeContext ents = new CompositeContext();
var ProductsQuery = from Products in ents.Products
orderby Products.ProductName
select Products;