自动映射多对多的映射混淆

时间:2017-07-12 12:15:18

标签: c# automapper

我有很多关系表,例如“User& Notification& UserNotification”及其实体,视图模型。

ViewModel和Entity类之间只有区别。 HasRead属性在NotificationViewModel中。如何将此实体映射到视图模型?我无法为HasRead属性实现此目的。

到目前为止我所做的是,

映射配置

CreateMap<Notification, NotificationViewModel>();
CreateMap<User, UserViewModel>().ForMember(dest => dest.Notifications, map => map.MapFrom(src => src.UserNotification.Select(x => x.Notification)));

通知类:

public class Notification : IEntityBase
{
    public Notification()
    {
        this.UserNotification = new HashSet<UserNotification>();
    }

    public int Id { get; set; }
    public string Header { get; set; }
    public string Content { get; set; }
    public System.DateTime CreateTime { get; set; }
    public bool Status { get; set; }

    public virtual ICollection<UserNotification> UserNotification { get; set; }
}

用户

public class User : IEntityBase
{
    public User()
    {
        this.UserNotification = new HashSet<UserNotification>();
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public bool Status { get; set; }

    public virtual ICollection<UserNotification> UserNotification { get; set; }
}

UserNotification 类:

public class UserNotification : IEntityBase
{
    public int Id { get; set; }
    public int UserId { get; set; }
    public int NotificationId { get; set; }
    public bool HasRead { get; set; }

    public virtual Notification Notification { get; set; }
    public virtual User User { get; set; }
}

UserViewModel

public class UserViewModel : IValidatableObject
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Email { get; set; }
    public string PhoneNumber { get; set; }
    public bool Status { get; set; }

    public IList<NotificationViewModel> Notifications { get; set; }
}

NotificationViewModel

public class NotificationViewModel
{
    public int Id { get; set; }
    public string Header { get; set; }
    public string Content { get; set; }
    public System.DateTime CreateTime { get; set; }
    public bool Status { get; set; }
    public bool HasRead { get; set; } // this is the difference
}

1 个答案:

答案 0 :(得分:2)

为了修复HasRead,您可以使用AfterMap(Action<TSource, TDestination> afterFunction)功能。它不像其他的自动播放器那么优雅,但它可能有效。

CreateMap<User, UserViewModel>()
    .ForMember(dest => dest.Notifications, map => map.MapFrom(src => src.UserNotification.Select(x => x.Notification)))
    .AfterMap((src, dest) =>
    {
        foreach (var notificationVM in dest.Notifications)
        {
            notificationVM.HasRead = src.UserNotification.Where(x => x.NotificationId == notificationVM.Id).Select(x => x.HasRead).FirstOrDefault();
        }
    });