2012-01-12 6 views
0

これは具体的な質問です。 C#、EF4.1、Mapperを使用してwcfサービスをコーディングしています。 ストアドプロシージャを使用したくない...とにかく。問題は、dbのアドレスフィールドを編集することです。しかし、編集したアドレスをdbに保存することはできません。Entity FrameworkとMapperを使用してデータベースフィールドを更新/編集する方法

public int EditAddress(int userId, Address address) 
    { 
     using(var mobileServiceContext = new MobileServiceContext()) 
     { 
      Address oldAddress = mobileServiceContext.Addresses.FirstOrDefault(p => p.UserId == userId && p.AddressId == address.AddressId); 
      Address lastAddress = Mapper.Map(address, oldAddress); 

      //save new-last address with ? HOW ? 
      //mobileServiceContext.Addresses.Attach(updatedAddress); //doesn't work 
      mobileServiceContext.SaveChanges(); 
     } 

     return address.AddressId; 
    } 

ここに編集した機能があります。

public int EditAddress(int userId, Address address) 
    { 
     using(var mobileServiceContext = new MobileServiceContext()) 
     { 
      Address oldAddress = mobileServiceContext.Addresses.FirstOrDefault(p => p.UserId == userId && p.AddressId == address.AddressId); 
      Address lastAddress = Mapper.Map(address, oldAddress); 

      mobileServiceContext.Addresses.Attach(lastAddress); //error on this line 
      mobileServiceContext.ObjectStateManager.ChangeObjectState(lastAddress, EntityState.Modified); 
      mobileServiceContext.SaveChanges(); 
     } 

     return address.AddressId; 
    } 

注:「アドレスアドレス」クラスにはすでにaddress.Idフィールドがあります。

私たちがここで作ったのはとても複雑なデザインで、読者のために読むのも難しいです。

答えて

0

代わりに、このシナリオでAutoMapperを使用しての、次のことができます。我々は、データモデルをマッピングしていないので、私はAutoMapperの必要性や、ここで任意のマッピング・ユーティリティが表示されていない

//this assumes that the AddressId in address is exists in the database: just attach it to the addresses set 
mobileServiceContext.Addresses.Attach(address); 
//this tells ef that the object is in a modified state 
mobileServiceContext.ObjectStateManager.ChangeObjectState(address, entityState.Modified); 
//savechanges will now update the database 
mobileServiceContext.SaveChanges(); 

(またはそれらの線に沿って何かを行う)。

+0

ありがとうございました。それは一度働いた。私たちがそれを2回目にしようとすると、このエラーが発生しています。 (on ... Addresses.Attach(address);) "同じキーを持つオブジェクトが既にObjectStateManagerに存在します。ObjectStateManagerは同じキーを持つ複数のオブジェクトを追跡できません。内部例外に役立つ情報はありません –

+0

@LostInLib - 問題ありません:)申し訳ありませんが、私はコメントの最初の部分だけを読んでいます。 – Skyrim

+0

同じコンテキストに同じオブジェクトを2回アタッチしようとしていますか? – Skyrim

関連する問題