开发者

Automapper and Entity Framework Code First Not Working Correctly

I am trying to use Automapper with Entity Framework Code First 4.1. I can't get a save/update to work correctly 100% of the time.

The first issue is if I don't use UseDestinationValue() on the object then my DTO won't map its properties to the Entity. Then if I don't use UseDestinationValue() the dynamically created proxy object loses some properties, and the property Address gets a new entity on every update.

Mapper.CreateMap<GymModel, Gym>(); <-- loses Entity Framework proxy properties for update, works fine on insert

or

Mapper.CreateMap<GymModel, Gym>()
.ForAllMembers(q => q.UseDestinationValue()); <-- Doesn't map DTO to Entity

and/or this doesn't work either

var gym = Mapper.CreateMap<GymModel, Gym>();
            gym.ForAllMembers(q => q.UseDestinationValue());
            gym.ForMember(q => q.DateCreated, o => o.MapFrom(s => s.DateCreated));

Service

public void Save(GymModel model)
{
    var item = new Gym()
  开发者_JAVA技巧  {
        Address = new Address()
    };

    if (model.Id > 0)
    {
        Expression<Func<Gym, bool>> where = q => q.Id == model.Id;
        Expression<Func<Gym, object>> address = q => q.Address;

        item = _gymsRepository.Get(new [] { address }, where);
    }

    model.Address.Id = item.AddressId;

    Mapper.Map(model, item);

AddressModel

public class AddressModel : IAddressModel
    {
        public int Id { get; set; }
        public string Location { get; set; }
        public string StreetAddress { get; set; }
        public string ExtendedAddress { get; set; }
        public string City { get; set; }
        public string StateRegion { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }

        public double? Latitude { get; set; }
        public double? Longitude { get; set; }
}

Address

[Table("Address", Schema = "GrassrootsHoops")]
    public class Address
    {
        [Key]
        public int Id { get; set; }
        public string Location { get; set; }
        public string StreetAddress { get; set; }
        public string ExtendedAddress { get; set; }
        public string City { get; set; }
        public string StateRegion { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }

        public double? Latitude { get; set; }
        public double? Longitude { get; set; }
    }


I went ahead and did this below and it stopped recreating a new address on a insert. If anyone knows a better way without explicitly telling the address to map and ignoring it on the parent please post it.

        Mapper.Map(model, item);
        Mapper.Map(model.Address, item.Address);

Mapper.CreateMap<GymModel, Gym>()
.ForMember(d => d.Address, o => o.Ignore());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜