2011-01-17 10 views
2

小さな独立したアプリケーションをいくつか構築しなければなりません。これはUSBデバイスにコピーして、そこから実行することができます。だから、まずはEFコードを使ってSQL Server CEデータベースに接続するWPFを使うことを考えていました。SQL Server CEを使用したアーキテクチャ

私の質問は、私が使用すべきアーキテクチャについてです。アプリはスタンドアロンですが、私はまだドメインからデータを切り離して、レイヤーをきれいに分離したいと考えています。しかし、私はそれをあまりにも複雑にしたくありません。

したがって、基盤となるドメイン層(ドメインロジックを持つドメインオブジェクト)とリポジトリ(最初にEFコードを使用する)を使用するUIレイヤー(WPF/MVVM)が必要です。

私の質問は、この場合、EFを動作させるためにどのようなパターンを使用する必要がありますか?このようなシナリオでCRUD操作を実装する方法を示す例がありますか?たとえば、1つのコンテキストを作成して開いておく必要があります。必要に応じて、作業パターンの単位を実装し、オブジェクトを他のコンテキストに添付する必要がありますか?

あなたはまったく異なる方法でやっていますか?

アドバイスをいただきありがとうございます。

答えて

2

EFコンテキストはできるだけ短時間開いておく必要があります。好ましくはusingステートメント内で使用します。

private static void ApplyItemUpdates(SalesOrderDetail originalItem, 
    SalesOrderDetail updatedItem) 
{ 
    using (AdventureWorksEntities context = 
     new AdventureWorksEntities()) 
    { 
     context.SalesOrderDetails.Attach(updatedItem); 
     // Check if the ID is 0, if it is the item is new. 
     // In this case we need to chage the state to Added. 
     if (updatedItem.SalesOrderDetailID == 0) 
     { 
      // Because the ID is generated by the database we do not need to 
      // set updatedItem.SalesOrderDetailID. 
      context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added); 
     } 
     else 
     { 
      // If the SalesOrderDetailID is not 0, then the item is not new 
      // and needs to be updated. Because we already added the 
      // updated object to the context we need to apply the original values. 
      // If we attached originalItem to the context 
      // we would need to apply the current values: 
      // context.ApplyCurrentValues("SalesOrderDetails", updatedItem); 
      // Applying current or original values, changes the state 
      // of the attached object to Modified. 
      context.ApplyOriginalValues("SalesOrderDetails", originalItem); 
     } 
     context.SaveChanges(); 
    } 
} 

コンテキストにエンティティをアタッチattachsと呼ばれる方法で、あります:

private static void AttachRelatedObjects(
    ObjectContext currentContext, 
    SalesOrderHeader detachedOrder, 
    List<SalesOrderDetail> detachedItems) 
{ 
    // Attach the root detachedOrder object to the supplied context. 
    currentContext.Attach(detachedOrder); 

    // Attach each detachedItem to the context, and define each relationship 
    // by attaching the attached SalesOrderDetail object to the EntityCollection on 
    // the SalesOrderDetail navigation property of the now attached detachedOrder. 
    foreach (SalesOrderDetail item in detachedItems) 
    { 
     currentContext.Attach(item); 
     detachedOrder.SalesOrderDetails.Attach(item); 
    } 
} 

http://msdn.microsoft.com/en-us/library/bb896271.aspx

は、
関連する問題