Creating navigation code-first results in the error: does not declare a navigation property with the name

query.Include("Store_Location").Load();

throws:

An exception of type ‘System.InvalidOperationException’ occurred in EntityFramework.SqlServer.dll but was not handled in user code

Additional information: A specified Include path is not valid. The EntityType ‘Model.Order’ does not declare a navigation property with the name ‘Store_Location’.

I used the following code in order to create the navigation code-first:

public partial class Order
{

    public Nullable<int> Store_Location_ID { get; set; }

    public virtual Store_Location Store_Location { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

}



public partial class Store_Location
{

    public int ID { get; set; }

    public virtual ICollection<Order> Orders { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]

}

https://docs.microsoft.com/en-us/ef/ef6/fundamentals/relationships

Do I need to use the designer? Is there anything I need to do in order for the navigation to be created?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you create your database with code first approach, then your entities should not be partial classes. Define them like this:

public class Order
{
    public int? StoreLocationId { get; set; }
    public virtual StoreLocation StoreLocation { get; set; }
}


public class StoreLocation
{
    public int Id { get; set; }
    public virtual ICollection<Order> Orders { get; set; }
}

Then you should create a DbContext class:

 public class StoreDbContext : DbContext
 {
        public StoreDbContext(DbContextOptions<StoreDbContext> options) : base(options)
        {
        }

        public virtual DbSet<StoreLocation> StoreLocations { get; set; }
        public virtual DbSet<Order> Orders { get; set; }
 }

After creating a context you can use the ef commands to create your database. You can read more about ef core here: https://docs.microsoft.com/en-us/ef/core/get-started/?tabs=netcore-cli

If you define your classes like I did above, you can include your navigation properties strongly typed like this:

query.Include(order => order.StoreLocation);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x