Reputation: 785
I try to make database for sport application using Entity Framework 6.1.3 Code First. When I try to make database is throw me exception.
The ForeignKeyAttribute on property 'HomeTeamId' on type 'Match' is not valid. The navigation property 'TeamId' was not found on the dependent type 'Match'. The Name value should be a valid navigation property name.
My Team class
public class Team
{
private ICollection<Match> matches;
public Team()
{
this.matches = new HashSet<Match>();
}
public int Id { get; set; }
[Required]
[MinLength(5)]
[MaxLength(40)]
public string Name { get; set; }
public virtual ICollection<Match> Matches
{
get { return this.matches; }
set { this.matches = value; }
}
}
My Match class
public class Match
{
public int Id { get; set; }
[Column(Order = 1)]
[ForeignKey("TeamId")]
public int HomeTeamId { get; set; }
public virtual Team HomeTeam { get; set; }
[Required]
[Range(0, 255)]
public byte HomeTeamScore { get; set; }
[Column(Order = 1)]
[ForeignKey("TeamId")]
public int AwayTeamId { get; set; }
public virtual Team AwayTeam { get; set; }
[Required]
[Range(0, 255)]
public byte AwayTeamScore { get; set; }
}
Can anyone help me resolve this?
Upvotes: 0
Views: 5490
Reputation: 15294
You have two foreign keys....
AwayTeamId
HomeTeamId
They're both referencing
TeamId
EntityFramework should be able to figure out the relationships on it own from what you have, so try removing the ForeignKey
attribute and attempt an update.
Read the summary comments on ForeignKeyAttribute
/// <summary>
/// Denotes a property used as a foreign key in a relationship.
/// The annotation may be placed on the foreign key property and specify the associated navigation property name,
/// or placed on a navigation property and specify the associated foreign key name.
/// </summary>
So... your foreign key attribute should be set up like this...
[ForeignKey("AwayTeam")]
[ForeignKey("HomeTeam")]
I replicated your solution locally, removing the foreign key attributes and all other associated attributes, including the Id's themselves resolves the issue.
public virtual Arena Arena { get; set; }
public virtual Team HomeTeam { get; set; }
[Required]
[Range(0, 255)]
public byte HomeTeamScore { get; set; }
public virtual Team AwayTeam { get; set; }
[Required]
[Range(0, 255)]
public byte AwayTeamScore { get; set; }
As you can see, no AwayTeamId, no HomeTeamId
And this is what Entity Framework generates on the backend... You still have the one to many relationship, test it out, let me know if you have issues
Upvotes: 2