Search code examples
entity-frameworkmigrationef-code-firstentity-framework-migrationscode-first

How can I add two property in my model in EF code first from one model?


I want to add two properties from the city model:

after migration this error shows up:

Unable to determine the relationship represented by navigation 'City.Orders' of type 'ICollection'. Either manually configure the relationship, or ignore this property using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.

here is my code :

public class Order
{
    public virtual City FromCity { get; set; }
    public virtual City ToCity { get; set; }
}

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Order> Orders { get; set; }
}

Solution

  • I suppose your model is more complicated than just FromCity and ToCity because I don't think it's a good idea to store such information in a different table. Yet, You can use inheritance in this case.

    The table-per-hierarchy (TPH) pattern is used by default to map the inheritance in EF. TPH stores the data for all types in the hierarchy in a single table.

    However, for your scenario, you can have a base class that holds all related attributes.

    public class CityBase
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
    }
    

    Then suppose you need two entities as per your scenario:

    public class FromCity : CityBase
    {
        public virtual ICollection<Order> Orders { get; set; } = null!;
    }
    public class ToCity : CityBase
    {
        public virtual ICollection<Order> Orders { get; set; } = null!;
    }
    

    And the order entity:

    public class Order
    {
        public int Id { get; set; }
        public string OrderTitle { get; set; } = string.Empty;
        public virtual FromCity FromCity { get; set; } = null!;
        public virtual ToCity ToCity { get; set; } = null!;
    }
    

    This approach can solve your problem with a One-to-Many relationship between Orders and FromCity, ToCity as per below diagram:

    Relationship Diagram