I just recently started using Entity Framework 1.0 and I think I'm starting to feel the pain everyone is talking about. I am trying to use best practices, so I have a DTO set that maps to my objects and to my objects through AutoMapper.
The real catch is when I try to update an object. The first was that I could not find a way to create a new object, transfer data from my DTO, and still have an ObjectContext object that understands that it has been modified. I used the following code:
public VideoDTO UpdateVideo(VideoDTO pVideo) { Video video = new Video(); Mapper.Map(pVideo, video); context.Attach(video); //Successfully attaches context.ApplyPropertyChanges("Videos", video); // no changes made as far as entity knows b/c it was attached in it updated state context.SaveChanges(); //doesn't save the entity return pVideo; }
Then I realized, maybe I just need to first grab the entity from the database, attach to the context, call the Map method on Mapper, and then call SaveChanges. Here is what I did:
public VideoDTO UpdateVideo(VideoDTO pVideo) { Video video = context.Videos.Where(v => v.VideoId == pVideo.VideoId).FirstOrDefault(); Mapper.Map(pVideo, video);
Now we move on to the beautiful EF problem when you are not allowed to change the VideoId property because it is used by the EntityKey property for the Video object. Beautiful. I configured the mappings, so when I mapped my DTO to EF Entity, the EntityKey property will get the value. Now I need a way to make an exception for this matching rule, but I donβt know where to start. I believe that I could create a completely new matching rule right in this method and set the EntityKey and VideoId properties that will be ignored, but that seems pretty messy. Also, I'm not sure what the creation created at this stage will adhere to. If he overrides the initial setting that allowed the DTO to map the EntityKey value on the object, this could have the opposite effect in a completely different way.
Anyone have a better idea?
jason source share