I have three entities Card, User and Category.
A card can have a category and a user (the owner of the card).
I have used FluentAPI to tell Entity Framework the relations between the entities, however I get this error
There are multiple relationships between 'Card' and 'User' without configured foreign key properties.
when they are configured.
User
public class User
{
public int Id { get; set; }
[Required]
[MaxLength(MaxNameLength)]
public string FirstName { get; set; }
[Required]
[MaxLength(MaxNameLength)]
public string LastName { get; set; }
[Required]
[MaxLength(MaxNameLength)]
public string Username { get; set; }
public int Age { get; set; }
[Required]
public string ProfileImageUrl { get; set; }
public IEnumerable<Card> OwnedCards { get; set; } = new List<Card>();
public IEnumerable<Card> CurrentlySellingCards { get; set; } = new List<Card>();
public IEnumerable<Card> SoldCards { get; set; } = new List<Card>();
public IEnumerable<Card> BoughtCards { get; set; } = new List<Card>();
}
Card
public class Card
{
public int Id { get; set; }
[Required]
[MaxLength(MaxTitleLength)]
public string Title { get; set; }
[Required]
public string ImageUrl { get; set; }
public CardTypes CardType { get; set; }
[Column("OwnerId")]
public int UserId { get; set; }
public User User { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
Category
public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public IEnumerable<Card> Cards { get; set; } = new List<Card>();
}
FluentAPI:
protected override void OnModelCreating(ModelBuilder builder)
{
builder
.Entity<Card>()
.HasOne(c => c.Category)
.WithMany(c => c.Cards)
.HasForeignKey(c => c.CategoryId)
.OnDelete(DeleteBehavior.Restrict);
builder
.Entity<Card>()
.HasOne(c => c.User)
.WithMany(u => u.OwnedCards)
.HasForeignKey(c => c.UserId)
.OnDelete(DeleteBehavior.Restrict);
base.OnModelCreating(builder);
}