2012-04-02 19 views
1

Entity Framework 4.2では、私は0を持つことができるTripsエンティティを持っています* PlacesOfInterestと0 .. * Photos。興味のある場所には1トリップと0 .. *写真があります。写真には1つの旅行と0..1の観光スポットがあります。Entity Frameworkの3進関係

私は写真を追加しようとすると、私はこの方法を使用します。

public static Guid Create(string tripId, Model.Photo instance) 
    { 
     var context = new Model.POCOTripContext(); 
     var cleanPhoto = new Model.Photo(); 
     cleanPhoto.Id = Guid.NewGuid(); 
     cleanPhoto.Name = instance.Name; 
     cleanPhoto.URL = instance.URL; 
     //Relate the POI 
     cleanPhoto.PlaceOfInterest = Library.PlaceOfInterest.Get(instance.PlaceOfInterestId); 
     context.PlacesOfInterest.Attach(cleanPhoto.PlaceOfInterest); 
     //Relate the trip 
     cleanPhoto.Trip = Library.Trip.Get(new Guid(tripId)); 
     context.Trips.Attach(cleanPhoto.Trip); 
     //Add the photo 
     context.Photos.AddObject(cleanPhoto); 
     context.SaveChanges(); 
     return cleanPhoto.Id; 
    } 

私はこれをテストするとトリップが装着されたとき、私は以下の取得:

An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key. 

をトリップが表示されませんただし、PlacesOfInterestはAttachステートメントの前に実行されます。私はこの仕組みが分からない、誰かが明確にすることができますか?

編集:ここではPOIとトリップゲッターが

context.Trips.Include("PlacesOfInterest").... 

...

public static Model.Trip Get(Guid tripId) 
    { 
     using (Model.POCOTripContext context = new Model.POCOTripContext()) 
     { 
      var tripEntity = context.Trips.Include("PlacesOfInterest").Include("PlacesOfInterest.PoiAttributes").Include("Photos").FirstOrDefault(c => c.Id == tripId) ?? new Model.Trip(); 
      return tripEntity; 
     } 
    } 

    public static Model.PlaceOfInterest Get(Guid poiId) 
    { 
     using (Model.POCOTripContext context = new Model.POCOTripContext()) 
     { 
      var poiEntity = context.PlacesOfInterest.Include("PoiAttributes").FirstOrDefault(c => c.Id == poiId) ?? new Model.PlaceOfInterest(); 
      return poiEntity; 
     } 
    } 

おかげ

S

+0

関連するアイテムを再度添付する必要はありません(関連するアイテムが既に添付されている限り、Attachコールは重複していると思います)セッターを介して)。あなたはアタッチなしで試しましたか? –

+0

はい、挿入しようとします。この質問を参照してください:http://stackoverflow.com/questions/9915216/why-does-adding-a-child-element-to-my-entity-framework-try-and-insert-a-new-pare –

+0

できますか'Library.Trip.Get(...)'と 'Library.PlaceOfInterest.Get(...)'にコードを表示しますか? – Slauma

答えて

1

これは...とPlacesOfInterestをロードします旅行。他の文脈に旅行を添付するときには、trip.PlacesOfInterestも添付されます。すでにPlaceOfInterest(コレクション内にIDがPlaceOfInterest)が添付されているため、同じキーの同じタイプの2つのオブジェクトを接続しています。これにより、例外が発生します。

コードを単純化することができます。主キーがあるため、エンティティを読み込む必要はありません。

cleanPhoto.PlaceOfInterest = new PlaceOfInterest 
          { Id = instance.PlaceOfInterestId }; 
context.PlacesOfInterest.Attach(cleanPhoto.PlaceOfInterest); 

cleanPhoto.Trip = new Trip { Id = new Guid(tripId) }; 
context.Trips.Attach(cleanPhoto.Trip); 
+0

完璧、ありがとう!私は何かを学んだ! –

関連する問題