Efcore: Navigation backing fields without property

Created on 14 May 2018  路  5Comments  路  Source: dotnet/efcore

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; }
}
closed-question customer-reported

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.

All 5 comments

@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.

Was this page helpful?
0 / 5 - 0 ratings