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
関連するアイテムを再度添付する必要はありません(関連するアイテムが既に添付されている限り、Attachコールは重複していると思います)セッターを介して)。あなたはアタッチなしで試しましたか? –
はい、挿入しようとします。この質問を参照してください:http://stackoverflow.com/questions/9915216/why-does-adding-a-child-element-to-my-entity-framework-try-and-insert-a-new-pare –
できますか'Library.Trip.Get(...)'と 'Library.PlaceOfInterest.Get(...)'にコードを表示しますか? – Slauma