Home > OS >  How to handle nested object in Entities that have no other relation
How to handle nested object in Entities that have no other relation

Time:10-18

Consider the following class:

public class Country{
   public string Name {get;set;}
   public Coordinate Coordinate {get;set;}
}
public class Coordinate{
   public Latitude {get;set;}
   public Longitude {get;set;}
}

Now, when I create a migration, it creates two tables: Country and Coordinate with a mapping between the two tables.

Table: Country
[id, name, coordinateId]

Table: Coordinate
[id, latitude, longitude]

This feels shady, as the coordinate doesn't have a relation to anything else. It could also be stored in the same table.

I feel like the better way is to have 1 table [Country] with all the fields:

Table: Country
[id, name, coordinate_latitude, coordinate_longitude]

Is it acceptable in EF that there are a lot of tables for nested objects that are filled with data only used by its main parent? Or is there a way to 'flatten' the objects that is more efficient?

CodePudding user response:

https://docs.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/implement-value-objects

There is an example how to set up value objects as columns in the main table:

orderConfiguration.OwnsOne(p => p.Address) .Property(p=>p.Street).HasColumnName("ShippingStreet");

orderConfiguration.OwnsOne(p => p.Address) .Property(p=>p.City).HasColumnName("ShippingCity");

CodePudding user response:

Why not using SqlGeography

public class Country{
   public string Name {get;set;}
   public SqlGeography Coords {get;set;}
}

Else you can flatten the class anyway.

public class Country{
   public string Name {get;set;}
   public double Latitude {get;set;}
   public double Longitude {get;set;}
}
  • Related