1) I am trying to establish a relationship between two classes. So, I have the following class
public class Team
{
[Key]
public int Id { get; set; }
public string Team { get; set; }
public List<MatchGame> MatchGames { get; set; }
}
and
public class MatchGame
{
[Key]
public int Id { get; set; }
public int HomeTeamId { get; set; }
public Team HomeTeam { get; set; }
public int AwayTeamId { get; set; }
public Team AwayTeam { get; set; }
}
The configuration that I tried to perform the relashioship is
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MatchGame>()
.HasOne(h => h.HomeTeam)
.WithMany(m => m.MatchGames)
.HasForeignKey(k => k.HomeTeamId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<MatchGame>()
.HasOne(h => h.AwayTeam)
.WithMany(m => m.MatchGames)
.HasForeignKey(k => k.AwayTeamId)
.OnDelete(DeleteBehavior.NoAction);
}
the produced error is:
Cannot create a relationship between 'Team.MatchGames' and 'MatchGame.AwayTeam' because a relationship already exists between 'Team.MatchGames' and 'MatchGame.HomeTeam'. Navigation properties can only participate in a single relationship. If you want to override an existing relationship call 'Ignore' on the navigation 'MatchGame.AwayTeam' first in 'OnModelCreating'.
I have also seen the following threads but couldn't find the reason why the relationship couldn't establish.
EF code first: one-to-many twice to same collection type
https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/fluent/relationships
EFCore - How to have multiple navigation properties to the same type?
2) Also, in order not to create a new post: I wanted to have the public string Team { get; set; }
in the Team Class to be Unique. I tried some DataAnnotation that I have seen but didn't work. what do I have to use for this purpose.