1
我想用实体框架代码优先4.1使用Automapper。我无法获得保存/更新以在100%的时间内正常工作。自动映射器和实体框架代码首先不能正常工作
第一个问题是,如果我不在对象上使用UseDestinationValue()
,那么我的DTO将不会将其属性映射到实体。然后,如果我不使用UseDestinationValue()
,动态创建的代理对象会丢失一些属性,并且属性Address会在每次更新时获得一个新实体。
Mapper.CreateMap<GymModel, Gym>(); <-- loses Entity Framework proxy properties for update, works fine on insert
或
Mapper.CreateMap<GymModel, Gym>()
.ForAllMembers(q => q.UseDestinationValue()); <-- Doesn't map DTO to Entity
和/或本无法正常工作或
var gym = Mapper.CreateMap<GymModel, Gym>();
gym.ForAllMembers(q => q.UseDestinationValue());
gym.ForMember(q => q.DateCreated, o => o.MapFrom(s => s.DateCreated));
服务
public void Save(GymModel model)
{
var item = new Gym()
{
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; }
}
地址
[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; }
}
我有类似的问题。你有没有找到比这种方法更好的解决方案? – Yuck