简体   繁体   中英

Entity Framework multiple optional relationships of same type with fluentapi

I have a class that has two optional fields "TeamOne" of type "Team" and "TeamTwo" of type "Team". Teams can obviously exist without being asssigned to a game and shall not be deleted when a game gets deleted and vice versa.

Now I am trying to set the relationships this way:

HasOptional(x => x.TeamOne).WithOptionalDependent(x => x.Game).WillCascadeOnDelete(false);
HasOptional(x => x.TeamTwo).WithOptionalDependent(x => x.Game).WillCascadeOnDelete(false);

I am running into the error

Schema specified is not valid. Errors: The relationship 'Infrastructure.DAL.Match_TeamOne' was not loaded because the type 'Infrastructure.DAL.Team' is not available.

Am I doing something wrong here?

edit: 1 game : 1 TeamOne and 1 TeamTwo TeamOne and TeamTwo are assigned to 1 game max

You're trying to create two relationships with one inverse end . Both Game.TeamOne and Game.TeamTwo are related to Team.Game . However, when coming from Team , to which Game should Team.Game refer? The one in which it is TeamOne , or TeamTwo ? There's an ambiguity there. You'd need a second property of type Game to tie to TeamTwo . This would work:

HasOptional(x => x.TeamOne).WithOptionalDependent(x => x.HomeGame).WillCascadeOnDelete(false);
HasOptional(x => x.TeamTwo).WithOptionalDependent(x => x.AwayGame).WillCascadeOnDelete(false);

But I don't think this model can be right. Can a team really have only one Game ? That's an interesting competition model! I think teams can play in "many" games, and the mapping should look like this:

HasOptional(x => x.TeamOne).WithMany(x => x.HomeGames)
                  .WillCascadeOnDelete(false)
HasOptional(x => x.TeamTwo).WithMany(x => x.AwayGames)
                  .WillCascadeOnDelete(false)

... where HomeGames and AwayGames are public (virtual) ICollection<Game> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM