问题
When defining a many to many relationship EF Core mandates the use of a join class. I am trying to hide this join class.
In my scenario a Person (entity 1) plays many Sports (entity 2), so there is a PersonSport (entity 3) table.
Using Entity Framework Core I can do something like this:
modelBuilder.Entity<Person>()
.ToTable("Person")
.Property(p => p.Surname)
.HasField("_surname");
The class looks something like this:
private readonly string _surname;
public string Surname
{
get
{
return _surname;
}
}
EF Core will correctly create a database field for: Person.Surname. Say the Person table has a relationship with Sport i.e. a Person participates in many Sports. Therefore there is a junction table called: PersonSport. Is it possible to do this:
1) Add a readonly collection to the Person table:
private readonly List<PersonSport> _personSport;
2) Setup the join as follows (in the context):
modelBuilder.Entity<PersonSport>()
.HasOne<Person>(ps => ps.Person)
.WithMany("_personSport")
.HasForeignKey(sc => sc.PersonId)
.OnDelete(DeleteBehavior.Cascade);
I am trying to hide the PersonSport list. The user of the class will use the following instead:
public IReadOnlyCollection<Sport> sports => _personSport.Select(ps=> ps.Sport).ToList().AsReadOnly();
Is this possible? When I run: Add-Migration InitialCreate; the error is
Value cannot be null.
来源:https://stackoverflow.com/questions/54025974/is-it-possible-to-hide-the-collection-which-defines-the-relationship