Automapper with Entity Framework Core recursive issue - c#

I have a many-to-many relationship with EF Core 2.x.
I have created 3 classes:
public class Place
{
public string Name {get; set;}
public int Id {get; set;}
public ICollection<PlaceUser> Users {get; set;}
}
public class User
{
public string Name {get; set;}
public int Id {get; set;}
public ICollection<PlaceUser> Places {get; set;}
}
public class PlaceUser
{
public int UserId{get; set;}
public User User{get; set;}
public int PlaceId{get; set;}
public Place Place{get; set;}
}
public class PlaceDto
{
public string Name {get; set;}
public int Id {get; set;}
public ICollection<PlaceUserDto> Users {get; set;}
}
In my dbcontext, I set up the relationship. Everything works well.
But when I want to Map my Dto Place to my Place Object in my object place I have a recursivity and overflow exception:
I have:
Place
|-> Users
|-> User
|-> Place
|-> Users
|-> ...
I tried in my config of mapper to use depth but it's not working.
The only workaround I have found is:
if(place!=null && place.Users!=null)
{ // I set all the place.Users[i].Place = null; and place.Users[i].User=null;}
But it's an ugly solution and not convenient at all.
So which solution can I use?
Thanks,
I added the automapper config:
configuration.CreateMap<Place, PlaceDto>().MaxDepth(1);

https://stackoverflow.com/a/48824922/8101300
https://stackoverflow.com/a/57134333/8101300
CreateMap<Foo, Bar>().PreserveReferences();

Related

How to get records from table that depends on another tables in entity framework core?

I want to get some records from Database that depends on three tables.
Three tables are:
1.Company(Id,Name)
2. Car(Id,CompanyId,Name)
3. Showroom(Id,CarId,Name)
Now a one company contains many cars and many cars may exist in many showrooms.
I want to get records from showroom table where company '2' cars exist along with cars. Is it possible to do it in entity framework core?
I think your entities will be like :
Company
public class Company
{
public int Id {get; set;}
public string Name {get; set;}
public ICollection<Car> Cars {get; set;}
}
Car:
public class Car
{
public int Id{get; set;}
public string Name {get; set;}
public int CompanyId{get; set;}
public Company Company {get; set;}
}
ShowRoom:
public class ShowRoom
{
public int Id{get; set;}
public string Name {get; set;}
public int CarId{get; set;}
public Car Car{get; set;}
}
In your method:
var context = new SomeContext();
var showRooms= context.ShowRooms
.Include(x=> x.Car)
.ThenInclude(x=> x.Company)
.Where(x=> x.Car.Company.Id== 2)
.ToList();

Entity Framework one-to-zero with different tables

I am wondering if it is possible to make one table related to many.
This is what I got now (working one-to-zero-or-one relation between Report and ReportHeader):
public class Report
{
public int Id {get; set;}
public ReportHeader ReportHeader {get; set;}
[ForeignKey("ReportHeader")]
public int ReportHeaderId {get; set;}
}
public class ReportHeader
{
[Key, ForeignKey("Report")]
public int Id {get; set;}
public Report Report {get; set;}
}
At this point I want to add table named Style to Report BUT also to table ReportHeader. Thus, the relations would look like this:
Report
|--ReportHeader
| |-- Style
|
|-- Style
After that the classes should look like:
public class Report
{
public int Id {get; set;}
public ReportHeader ReportHeader {get; set;}
public Style Style {get; set;}
[ForeignKey("ReportHeader")]
public int ReportHeaderId {get; set;}
[ForeignKey("Style")]
public int StyleId {get; set;}
}
public class ReportHeader
{
[Key, ForeignKey("Report")]
public int Id {get; set;}
[ForeignKey("Style")]
public int StyleId {get; set;}
public Report Report {get; set;}
public Style Style {get; set;}
}
This is so much fun... until it comes to think about the Style class. At this point I have no idea how to design it. Is that even possible to make that class be in two relations with different tables?
public class Style
{
// ???
//[Key, ForeignKey("Report"), ForeignKey("ReportHeader")]
public int Id {get; set;}
public ReportHeader ReportHeader {get; set;}
public Report Report {get; set;}
}
At this case you should to mask your desired relation: one-to-one as many-to-one:
public BaseClass
{
//indeed, collection always will have zero or one items
public virtual ICollection<Style> styles {get; set;}
[NotMapped]
public Style style {
get { return styles.FirstOrDefault(); }
set { styles.Add(value); };
}
}
public class Report : BaseClass
{
//other stuff...
}
public class ReportHeader : BaseClass
{
//other stuff...
}
public class Style
{
public int Id {get; set;}
public virtual Report report {get; set;}
[Index(IsUnique = true)]//to ensure that relation is exactly one-to-one
public int? reportId {get; set;}
public virtual ReportHeader reportHeader {get; set;}
[Index(IsUnique = true)]//to ensure that relation is exactly one-to-one
public int? reportHeaderId {get; set;}
}

Automapper self referencing model projection

I've got a problem handling self referencing model in my application using Automapper Projections. This is how my models look like:
public class Letter
{
public int? ParentId {get; set;}
public Letter ParentLetter {get; set;
public int Id {get; set;}
public string Title {get; set;}
public string Content {get; set;}
public DateTime? ReceivedTime {get; set;}
public DateTime? SendingTime {get; set;}
public List<Destination> Destinations {get; set;}
public List<Letter> Responses {get; set;}
}
public class LetterView
{
public int? ParentId {get; set;}
public int Id {get; set;}
public string Title {get; set;}
public string Content {get; set;}
public DateTime? ReceivedTime {get; set;}
public DateTime? SendingTime {get; set;}
public List<DestinationView> Destinations {get; set;}
public List<LetterView> Responses {get; set;}
}
public class Destination
{
public int Id {get; set;}
public string Name {get; set;}
..
}
public class DestinationView
{
public int Id {get; set;}
public string Name {get; set;}
}
// The mapping:
CreateMap<Destination, DestinationView>
CreateMap<Letter, LetterView>
My problem is with mapping Letter to LetterView. The problem is somewhere with the Responses, I just can't figure out what should be changed.
Whenever running unit tests and asserting mapping configurations everything works, as well as mapping a letter with multiple responses to a view model.
However, whenever I get a letter with it's resposnes from the database (Entity framework 6), the projection to LetterView throws a stackoverflow exception.
Can anyone please explain me why this happens only on projection? What should I change?
A couple of options here, but usually the best choice is to set a max depth on the Responses. AutoMapper will try to spider the properties, and you've got a self-referencing DTO. First try this:
CreateMap<Letter, LetterView>()
.ForMember(d => d.Responses, opt => opt.MaxDepth(3));
Another option is to pre-wire your DTOs with a specific depth. You'd create a LetterView, and a ChildLetterView. Your ChildLetterView would not have a "Responses" property, giving you exactly 2 levels of depth on your DTO side. You can make this as deep as you want, but be very explicit in the DTO types in where they are in the hierarchy with Parent/Child/Grandchild/Greatgrandchild type names.
You probably have lazy loading enabled on your DbContext. Circular references may produce stack overflow exception. The best way to avoid it is to disable lazy loading :
context.ContextOptions.LazyLoadingEnabled = false;
// Bring entity from database then reenable lazy loading if needed
context.ContextOptions.LazyLoadingEnabled = true;
However, you will need to include all required navigation properties since EntityFramework will not brought them back while lazy loading is deactivated. Don't forget to re enable it after if you need it for other requests.

How to avoid circular references with AutoMapper?

I have the following models (and corresponding DTOs):
public class Link
{
public int Id {get; set;}
public int FirstLinkId {get; set;}
public int SecondLinkId {get; set;}
public virtual Link FirstLink {get; set;}
public virtual Link SecondLInk {get; set;}
}
public class OtherObject
{
public int Id {get; set;}
public int LinkId {get; set;}
public string Name {get; set;}
public virtual Link Link {get; set;}
}
In my scenario, I can have a Link object where FirstLink and/or SecondLink can be null, references to other objects, or references to the same object.
Now I want to load an OtherObject entity from the db using EF. I load the entity itself and also the Link object associated with it. This is done perfectly by EF.
In this particular case, both FirstLink and SecondLink are the same as Link, therefore, when automapping from model to dto it just keeps on mapping into oblivion.
My mapping is:
Mapper.CreateMap<OtherObject, OtherObjectDto>().Bidirectional()
.ForMember(model => model.LinkId, option => option.Ignore());
where Bidirectional() is this extension:
public static IMappingExpression<TDestination, TSource> Bidirectional<TSource, TDestination>(this IMappingExpression<TSource, TDestination> expression)
{
return Mapper.CreateMap<TDestination, TSource>();
}
Is there way to tell Automapper not to map further down the tree in this case?
The way I would handle this is to create separate DTO objects for the children:
public class Employee
{
public int Id {get; set;}
public string Name { get; set; }
public Employee Supervisor {get; set; }
}
public class EmployeeDto {
public int Id {get; set;}
public string Name { get; set; }
public SupervisorDto Supervisor { get; set; }
public class SupervisorDto {
public int Id {get; set;}
public string Name { get; set; }
}
}
Mapper.CreateMap<Employee, EmployeeDto>();
Mapper.CreateMap<Employee, EmployeeDto.SupervisorDto>();
Don't let your DTOs be recursive/self-referential. Be explicit in your structure on how deep you want it to go.
EF can't do recursive joins, you're only doing one level, so don't make your DTOs go nuts with infinitely deep relationships. Be explicit.

Should foreign Id properties be mapped from Model to Dto?

If I have the following model:
public class Customer
{
public int Id {get; set;}
public int CustomerTypeId {get; set;}
public virtual CustomerType {get; set;}
}
Should the Dto exclude foreign Id's to look like this:
public class CustomerDto
{
public int Id {get; set;}
public virtual CustomerType {get; set;}
}
And when using Graphdiff to update the object graph, will EF know that CustomerType maps to CustomerTypeId?
Yes, you need to use it but you can avoid virtual member declaration. If you use AutoMapper, then the mapping will be done automatically. So, your Dto will look like this:
public class CustomerDto
{
public int Id {get; set;}
public int CustomerTypeId {get; set;}
}
And the mapping:
Mapper.CreateMap<Customer, CustomerDto>();
Mapper.CreateMap<CustomerDto, Customer>();

Categories