2015年11月27日金曜日

Entity Framework database firstでクラスを作成する方法

database firstでクラスを作成する方法

 

■プロジェクトの作成とサンプルDBの追加

C#のプロジェクトの新規作成します。 EntityFrameworkの機能にフォーカスするために、 ここではコンソールアプリケーションを選択します。
便宜上、プロジェクト名は、EFSample という名前で話を進めます。

プロジェクトができたら、次に、App_Data フォルダをプロジェクトに新規追加します。
作成されたVisual StudioのプロジェクトのApp_Dataフォルダに、エクスプローラから Northwnd.mdf と Northwnd_log.ldf をドロップします。
ファイルが App_Dataフォルダにコピーされると同時に、プロジェクトに追加されます。

c01

■Entity Data Model 作成

  1. プロジェクトEFSample に Models フォルダを作成します。

  2. Model フォルダを右クリックし、[新しい項目の追加]を選びます。

  3. 新しい項目の追加ダイアログが表示されますので、[ADO.NET Entity Data Model ]を選択し、名前に "NorthwindContext"と入力し、[追加]ボタンを押します。

    c02
  4. [データベースからCode First] を選択し、次へ ボタンをクリックします。

    c03

    ※ 変な名前ですね。もっと良い訳はなかったんでしょうか?

  5. 新しい接続ボタンをおして、設定のプロパティダイアログで、データソースの 変更で、Microsoft SQL Server データベースファイル を選びます。

    C051

    c04


  6. データベースのファイル名では、先ほどのNorthwnd.mdf を指定し、OK ボタンを押します。

  7. ダイアログの下の入力欄に、"NorthwindConnection" と入力し、次へを押します。

    C52
  8. 「ファイルをプロジェクトにコピーし、接続を変更しますか?」 と聞いてきますが、いいえを選択します。
    ※ はっきり言ってこのメッセージは不要ですね。はいを押すとプロジェクトの直下に mdfファイルがコピーされてしまいます。
  9. 次のウィザード画面では、すべてのテーブルをモデルに含めるので、 テーブルにチェックを入れます。 さらに、「生成されたオブジェクトの名前を複数化または単数化する」にチェックし、 完了ボタンを押します。

    c08

  10. Models フォルダに、NorthwindContext.cs と、各テーブルに対応した C#のソースフィルが追加されていることを確認します。

    c09

実際に、これらのソースファイルに中身を確認してください。 いくつかの属性が追加されてはいますが、普通のC#のクラスである ことを確認できると思います。

NorthwindContext.cs には、Categories や Customersといった テーブル名を複数形にしたプロパティが定義されています。 EntityFramework では、これらのプロパティを使い、テーブルにアクセス することになります。


次のバージョンのEntityFrameworkでは、EDMXファイル([データベースからEF Degigner]で作成される)がサポートされないことがアナウンスされています。
そのため、このシリーズでは、EDMXを使わずに、[データベースからCode First]で、エンティティモデル を作成しています。Database Firstでも問題なくプログラムを書くことができます。

■Productsテーブルの参照

Productsテーブルからデータを取得してみましょう。
プログラムでは、先ほど作成した Product「EntityFrameworkエンティティクラス」を 経由して、Productsテーブルの各カラムにアクセスすることになります。 さっそく、このProductsテーブルにアクセスするコードを書いてみます。

  1. using LinqToEntitySample.Models;
  2. ...
  3.  
  4. static void Main(string[] args) {
  5. using (var db = new NorthwindContext()) {
  6. var query = from product in db.Products
  7. select product;
  8. foreach (Product p in query)
  9. Console.WriteLine("{0} | {1} | {2} | {3}",
  10. p.ProductID, p.ProductName, p.UnitPrice, p.QuantityPerUnit);
  11. Console.ReadLine();
  12. }
  13. }

実行すると、


  1. 1 | Chai | 18.0000 | 10 boxes x 20 bags
  2. 2 | Chang | 19.0000 | 24 - 12 oz bottles
  3. 3 | Aniseed Syrup | 10.0000 | 12 - 550 ml bottles
  4. 4 | Chef Anton's Cajun Seasoning | 22.0000 | 48 - 6 oz jars
  5. 5 | Chef Anton's Gumbo Mix | 21.3500 | 36 boxes
  6. 6 | Grandma's Boysenberry Spread | 25.0000 | 12 - 8 oz jars
  7. 7 | Uncle Bob's Organic Dried Pears | 30.0000 | 12 - 1 lb pkgs.
  8. .
  9. .
  10. .

と表示され、Productsテーブルからデータを取得できたことを確認できます。
NorthwindContext クラスは、[データベースからCode First]の追加で自動生成されたクラ スで、NorthwindContext.csで以下のように定義されています。
  1. public partial class NorthwindContext : DbContext {
  2. public NorthwindContext()
  3. : base("name=NorthwindContext") {
  4. }
  5.  
  6. public virtual DbSet Categories { get; set; }
  7. public virtual DbSet CustomerDemographics { get; set; }
  8. public virtual DbSet Customers { get; set; }
  9. public virtual DbSet Employees { get; set; }
  10. public virtual DbSet Order_Details { get; set; }
  11. public virtual DbSet Orders { get; set; }
  12. public virtual DbSet Products { get; set; }
  13. public virtual DbSet Regions { get; set; }
  14. 以下省略

先ほど利用した Productsプロパティも定義されていますね。 EntityFrameworkでは、このDbContextクラスの派生クラスのインスタンスを生成 することで、データベースにアクセスすることが可能になります。

先ほどのクエリ式では、Productsテーブルから全てのデータを取得しています。各カラムの値は、プロパティとしてアクセスできます。
なお、Productsテーブルを示すNorthwindContextクラスのプロパティ名はProductsと複数形になっている点に注目してください。単数形のProductは、1行分を表すクラスです。

2015年11月21日土曜日

ASP.NET MVC テーブル名の設定

ASP.NET MVCでテーブル名は、設定しないと自動的にクラス名+s になる

例 クラス名 User テーブル名 Users

例えばコードFirstでは無く、Database Firstなら、テーブル名を設定したい
その場合は、クラス名の下に

    public class DEBAN_HENKODbContext : DbContext
    {
        protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)  {
            base.OnModelCreating(modelBuilder);

            //こんな感じで好きな名前を定義します
            modelBuilder.Entity<DEBAN_HENKO>().ToTable("DEBAN_HENKO");
        }
    }

modelBuilderを使ってテーブル名を設定する

2015年11月7日土曜日

ASP.NET MVC Identityによるカスタムログイン

usernamagerを使えば楽なのだが
ユーザー管理は基幹システムで管理するので
Webサービス経由でログイン情報を取得する。

他のサンプルを見ても、usermanager経由だったので、ClaimsIdentityを生成する方法が
分からんので、単純にセッション変数を使ってログインを使用かな~と思ったが
何とかサンプルが有ったので、記述しておく。

AccountControllerを以下のように修正

using Microsoft.AspNet.Identity;  
using Microsoft.Owin.Security;  
using System.Security.Claims;  
using System.Web;  
using System.Web.Mvc;

namespace Mvc5AuthSample.Controllers  
{
    public class AccountController : Controller
    {
      public ActionResult Login()
      {
        return View();
      }

      [HttpPost]
      public ActionResult Login(string username, string password)
      {
        if (username == "alice" && password == "supersecret")
        {
           HttpContext.GetOwinContext().Authentication
             .SignOut(DefaultAuthenticationTypes.ExternalCookie);

           Claim claim1 = new Claim(ClaimTypes.Name, username);
           Claim[] claims = new Claim[] { claim1 };
           ClaimsIdentity claimsIdentity = 
             new ClaimsIdentity(claims,
               DefaultAuthenticationTypes.ApplicationCookie);

           HttpContext.GetOwinContext().Authentication
            .SignIn(new AuthenticationProperties() 
              { IsPersistent = false }, claimsIdentity);

           return Redirect("/Home");
        }
        else
        {
           ModelState.AddModelError("", 
            "Invalid username or password.");
        }

        return View();
      }
    }
}


元ネタ
http://aspnetguru.com/adding-authentication-to-asp-net-mvc-5/