Reputation: 23
How does one map many to many relationships?
One-to-one relationships are easy....
Assuming...
public class ProductDTO
{
public int Id { get; set; }
public string Name { get; set; }
public int SupplierId { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double Cost { get; set; }
public Supplier Supplier { get; set; }
}
public class Supplier
{
public int Id { get; set; }
public string Name { get; set; }
public int Rating { get; set; }
public ICollection<Product> Products { get; set; }
}
Mapper.CreateMap<Product, ProductDTO>()
.ForMember(d => d.SupplierId, m => m.MapFrom(s => s.Supplier.Id));
Works assuming every product has only one supplier and a supplier can have many products. How do I map it if a product can also have many suppliers?
I changed supplier line in Products to
public ICollection<Supplier> Supplier { get; set; }
and in ProductDTO doing the same
public ICollection<int> SupplierId { get; set; }
How do I alter CreateMap since the Ids are now collections? Autocomplete no longer shows Id and all I get are functions.
I'm new to C# so I many be missing something obvious. Am I supposed to iterate in a for loop and map the ids one by one?
Upvotes: 2
Views: 1075
Reputation: 5103
You may try to use:
Mapper.CreateMap<Product, ProductDTO>()
.ForMember(d => d.SupplierIds, m => m.MapFrom(p => p.Suppliers.Select(s => s.Id)));
Another option:
Mapper.CreateMap<Supplier, int>().ConvertUsing(s => s.Id);
Mapper.CreateMap<Product, ProductDTO>()
.ForMember(d => d.SupplierIds, m => m.MapFrom(p => p.Suppliers));
One more thing if you are this using DTO to pass data from Web/WCF service you may consider using
public ICollection<SupplierDTO> Supplier { get; set; }
instead if passing supplier ids only. In most cases it's better (and more effective) to pass more data in one call to the service than doing few calls.
Upvotes: 1