Is this possible to achieve?:
// It should be many-to-many but I made it one-to-many just to demonstrate the problem so the Director can be director only of one movie.
class Movie
{
public int Id { get; set }
// I want it to be navigation property, but without property defined explicitly in the model
private ICollection<Director> _directors;
}
class Director
{
public int Id { get; set; }
public string Name { get; set; }
public int? MovieId { get; set; }
[ForeignKey("MovieId")]
public Movie Movie { get; set; }
}
Please take a look at
https://docs.microsoft.com/en-us/ef/core/modeling/backing-field#fields-without-a-property
@SSkovboiSS I've tried it before but it said that collection is not supported, or something like that. It just didn't work.
modelBuilder.Entity<Movie>().Property("Directors").HasField("_directors");
I also tried:
modelBuilder.Entity<Movie>().Property<ICollection<Director>>("Directors").HasField("_directors");
and
modelBuilder.Entity<Movie>().Property<HashSet<Director>>("Directors").HasField("_directors");
How about just:
modelBuilder.Entity<Movie>().Property("_directors");
@enemyofthedawn Assuming you are using EF Core 2.1, then configure the relationship using the fluent API in the normal way, but use strings for the fields. For example:
C#
modelBuilder
.Entity<Director>()
.HasOne(e => e.Movie)
.WithMany("_directors");
@SSkovboiSS You're examples are for non-navigation properties. Navigation properties are different because they are tightly associated with an FK to form a relationship and not just mapped directly to something in the database.
@ajcvickers but how to eager load it with Include then? I guess
.Include("_directors")
Yep that worked.
Most helpful comment
@enemyofthedawn Assuming you are using EF Core 2.1, then configure the relationship using the fluent API in the normal way, but use strings for the fields. For example:
C# modelBuilder .Entity<Director>() .HasOne(e => e.Movie) .WithMany("_directors");@SSkovboiSS You're examples are for non-navigation properties. Navigation properties are different because they are tightly associated with an FK to form a relationship and not just mapped directly to something in the database.