The property 'x' is not a navigation property of entity type 'y'

asp.net-core c# entity-framework-core

Question

I'm using EF Core with ASP Core 2.0. Using latest Identity framework. I get this exception on page All.

InvalidOperationException: The property 'User' is not a navigation property of entity type 'Gallery'. The 'Include(string)' method can only be used with a '.' separated list of navigation property names.

ApplicationUser looks like:

public class ApplicationUser : IdentityUser<Guid>
{
    public ICollection<Gallery> Galleries { get; set; }
}

Entity Gallery looks like:

public class Gallery
{
    public int Id { get; set; }
    public Guid UserId { get; set; }
    public string Title { get; set; }
    public int? ArticleId { get; set; }
    public string Photos { get; set; }
    public DateTime CreatedAt { get; set; }
    public DateTime UpdatedAt { get; set; }

    public Article Article { get; set; }
    public ApplicationUser User { get; set; }

    [NotMapped]
    public List<string> PhotosList
    {
        get { return Photos?.Split('|').ToList(); }
        set { Photos = string.Join("|", value); }
    }
}

Controller for View looks like:

public async Task<IActionResult> All()
    {
        var databaseContext = db.Galleries.Include(x => x.Article).Include(x => x.User);

        return View(await databaseContext.ToListAsync());
    }

I have no idea why it dont crash on Article..

Database is up-to-date.

1
10
10/19/2017 8:26:02 PM

Accepted Answer

add a ForeignKey attribute

using System.ComponentModel.DataAnnotations.Schema;

...

[ForeignKey("Article")]
public int? ArticleId { get; set; }

[ForeignKey("User")]
public Guid UserId { get; set; }

You can also put the attribute on the navigation property

[ForeignKey("UserId")]
public ApplicationUser User { get; set; }

Also, make sure your dbContext inherits from IdentityDbContext<ApplicationUser, ...>

1
10/20/2017 2:14:34 PM

Popular Answer

You can run into this if you manually add extra properties to Models.

To troubleshoot it, run SQL Profiler and capture the RAW SQL, execute the SQL against the database and see why the query doesn't work, ie which property 'x' is not a navigation property of entity type 'y'.

Then go to the model and remove the extra property you added manually.

ps If you dont have a SQL dB you can use another profiler. Alternatively just check the Diff's in source control.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow