public class Room
{
public Guid Id { get; set; }
public List<RoomUser> RoomUsers { get; set; }
}
public class User
{
public Guid Id { get; set; }
public List<RoomUser> UserRooms { get; set; }
}
public class RoomUser
{
public Guid RoomId { get; set; }
public Guid UserId { get; set; }
public Room Room { get; set; }
public User User { get; set; }
public string Status { get; set; }
}
public class RoomDto
{
public Guid Id { get; set; }
public string Status { get; set; }
public List<UserDto> Users { get; set; }
}
public class UserDto
{
public Guid Id { get; set; }
public string Status { get; set; }
public List<RoomDto> Rooms { get; set; }
}
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Room, RoomDto>()
.ForMember(o => o.Users, exp => exp.MapFrom(m => m.RoomUsers));
cfg.CreateMap<User, UserDto>()
.ForMember(o => o.Rooms, exp => exp.MapFrom(m => m.UserRooms));
cfg.CreateMap<RoomUser, UserDto>()
.ForMember(o => o.Id, exp => exp.MapFrom(m => m.User.Id));
//.IncludeMembers(o => o.User);
cfg.CreateMap<RoomUser, RoomDto>()
.ForMember(o => o.Id, exp => exp.MapFrom(m => m.Room.Id));
//.IncludeMembers(o => o.Room);
});
var mapper = config.CreateMapper();
var room = new Room
{
Id = Guid.NewGuid(),
RoomUsers = new List<RoomUser>()
};
var user = new User
{
Id = Guid.NewGuid(),
UserRooms = new List<RoomUser>()
};
var link = new RoomUser
{
User = user,
Room = room,
RoomId = room.Id,
UserId = user.Id,
Status = "admin"
};
room.RoomUsers.Add(link);
user.UserRooms.Add(link);
var byRoom = mapper.Map<RoomDto>(room);
Console.WriteLine(JsonConvert.SerializeObject(byRoom, Formatting.Indented));
var byUser = mapper.Map<UserDto>(user);
Console.WriteLine(JsonConvert.SerializeObject(byUser, Formatting.Indented));