【ADO.NET Entity Framework】Object Serviceの使用

こんにちは、こだかです。

前回に引き続きまして、EntityDataModel(EDM)に対するクエリーをご紹介します。

1.EntityClientを直接扱う方法
 ・・・EntitySQL
2.ObjectQueryから問い合わせをかける方法
 ・・・EntitySQL
 ・・・Query builder メソッド
 ・・・Linq to Entity
今回は2のObjectService(ObjectQuery)を使用してみましょう。

ObjectServiceは、データのクエリーや  insert, update, deleteを可能にする Entity Frameworkのコンポーネントです。
EDM内で定義された型(ObjectQuery<T>)で戻り値が返り、コントロールのバインド等も可能です。

まず、Query builder メソッドを使用した例になります。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using pubsModel;
    using System.Data.Objects;

    namespace EF2
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (pubsEntities pubsContext = new pubsEntities())
                {
                    string fname = "Maria";

                    ObjectQuery<employee> emps = pubsContext.employee.Where(
                        "it.fname = @fname", new ObjectParameter("fname", fname)).OrderBy("it.lName");
                    foreach (employee emp in emps)
                    {
                        Console.WriteLine("[ObjectService] employeeName :{0} - {1}", emp.fname, emp.lname);
                    }
                    pubsContext.Connection.Close();
                }
            }
        }
    }

次に、EntitySQLを使用してみましょう。
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using pubsModel;
    using System.Data.Objects;

    namespace EF2
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (pubsEntities pubsContext = new pubsEntities())
                {
                    string fname = "Maria";
                    string entitySQL = "SELECT VALUE c FROM pubsEntities.employee AS c WHERE c.fname = @fname";
                   ObjectQuery<employee> emps = pubsContext.CreateQuery<employee>(entitySQL , new ObjectParameter("fname", fname));
                    foreach (employee emp in emps)
                    {
                        Console.WriteLine("[ObjectService] employeeName :{0} - {1}", emp.fname, emp.lname);
                    }
                    pubsContext.Connection.Close();
                }
            }
        }
    }

こだかたろう