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.
A navigation property is an optional property on an entity type that allows for navigation from one end of an association to the other end. Unlike other properties, navigation properties do not carry data.
The [ForeignKey(name)] attribute can be applied in three ways: [ForeignKey(NavigationPropertyName)] on the foreign key scalar property in the dependent entity. [ForeignKey(ForeignKeyPropertyName)] on the related reference navigation property in the dependent entity.
Principal key: The properties that uniquely identify the principal entity. This may be the primary key or an alternate key. Foreign key: The properties in the dependent entity that are used to store the principal key values for the related entity.
Entity framework supports three types of relationships, same as database: 1) One-to-One 2) One-to-Many, and 3) Many-to-Many. We have created an Entity Data Model for the SchoolDB database in the Create Entity Data Model chapter.
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, ...>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With