Is it possible to hide the collection, which defines the relationship?

白昼怎懂夜的黑 提交于 2019-12-11 00:18:27

问题


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 isValue cannot be null.

来源:https://stackoverflow.com/questions/54025974/is-it-possible-to-hide-the-collection-which-defines-the-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!