How to fix 'Unable to determine the relationship represented by navigation property' error in Entity Framework

后端 未结 1 1202
暖寄归人
暖寄归人 2021-01-12 10:02

When I try to register a user on my .NET Core 2.1 website (using identity) I get the following error:

\"InvalidOperationException: Unable to determin

相关标签:
1条回答
  • 2021-01-12 10:22

    UPDATE

    You have multiple options here:

    Option 1 with result 1

    City Class becomes:

    public partial class City
    {
        public City()
        {           
            Connections = new HashSet<Connection>();
        }
    
        public int Id { get; set; }
        public string Name { get; set; }
        public string Country { get; set; }
    
        public ICollection<Connection> Connections { get; set; }
    }
    

    Connection Class becomes:

    public partial class Connection
    {
        public Connection()
        {
        }
    
        public int Id { get; set; }
    
        public int StartCityId { get; set; }
        public int EndCityId { get; set; }
    
        public int AantalMinuten { get; set; }
        public double Prijs { get; set; }     
    }
    

    Your OnModelCreating becomes:

    modelBuilder.Entity<City>().HasMany(city => city.Connections)
                               .WithRequired().HasForeignKey(con => con.EndCityId);
    
    modelBuilder.Entity<City>().HasMany(city => city.Connections)
                               .WithRequired().HasForeignKey(con => con.StartCityId);
    

    OR you can do something like this as well wchich would be option 2 with results 2:

    City Class becomes:

    public partial class City
    {
        public City()
        {           
            Connections = new HashSet<Connection>();
        }
    
        public int Id { get; set; }
        public string Name { get; set; }
        public string Country { get; set; }
    
        public ICollection<Connection> Connections { get; set; }
    }
    

    Connection Class becomes:

    public partial class Connection
    {
        public Connection()
        {
        }
    
        public int Id { get; set; }
    
        public virtual ICollection<City> Cities { get; set; }
    
        public int AantalMinuten { get; set; }
        public double Prijs { get; set; }     
    }
    

    And you don't have to do anything in your OnModelCreating.

    0 讨论(0)
提交回复
热议问题