PDA

View Full Version : Update موجودیت فرزند در رابطه یک به چند با AutoMapper



Spate
شنبه 06 مهر 1398, 20:13 عصر
با سلام
من دو موجودیت به شکل زیر دارم:


public class ClientInfo
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public GenderType Gender { get; set; }
public string IdentityNumber { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public string Email { get; set; } = null;
public string Country { get; set; }
public string Province { get; set; }
public string City { get; set; }
public bool IsActive { get; set; }


public ICollection<CompanionInfo> CompanionInfo { get; set; }


}


public class CompanionInfo
{
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime BirthDate { get; set; }
public GenderType Gender { get; set; }
public string IdentityNumber { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string Address { get; set; }
public CompanionTypes CompanionType { get; set; }
public Guid ClientInfoId { get; set; }
public ClientInfo ClientInfo { get; set; }
}

***کلاس Dto متناظر با هر کدام از موجودیت‌ها به همان شکل پیاده سازی شده!
به همراه پروفایل AutoMapper:

public class ClientInfoApplicationAutoMapperProfile : Profile
{
public ClientInfoApplicationAutoMapperProfile()
{
AllowNullCollections = true;


CreateMap<ClientInfo, ClientInfoDto>().ReverseMap()
.ForMember(d => d.CompanionInfo, m => m.MapFrom(s => s.CompanionInfo));


CreateMap<ClientInfo, CreateUpdateClientInfoDto>().ReverseMap()
.ForMember(d => d.CompanionInfo, m => m.MapFrom(s => s.CompanionInfo))
.ForAllMembers(opt => opt.Condition((s, d, m) => m != null));


CreateMap<CompanionInfo, CompanionInfoDto>().ReverseMap()
.ForAllMembers(opt => opt.Condition((s, d, m) => m != null));
}
}

همه چیز (افزودن و ویرایش در موجودیت والد و همچنین افزودن در موجودیت فرزند) درست انجام میشه، اما زمانی که قصد بروزرسانی موجودیت فرزند رو داشته باشم، درصورت خالی بودن فیلدها (برای مثال در صورت ویرایش نام به تنهایی)، مقدار فیلدهای خالی بصورت نال در دیتابیس ذخیره میشه.
راه حلی برای این موضوع وجود داره (با استفاده از AutoMapper)?