so I want to create the relationships between my Model classes (Booking and Person). I found a tutorial for that here.
I need the HasMany - WithMany Methods. When I try HasOne everything works fine. But as soon as I switch it to HasMany the error code in the title comes up.
I found a example in the Internet and it somehow works for him.
My Model classes:
namespace BookADesk.API.Models
{
public class Booking
{
public Guid Id { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public Guid DeskId { get; set; }
public Desk Desk { get; set; }
public Guid PersonId { get; set; }
public Person Persons { get; set; }
}
}
namespace BookADesk.API.Models
{
public class Person
{
public Guid Id { get; set; }
public string Nickname { get; set; }
public string SurName { get; set; }
public string GivenName { get; set; }
public ICollection<Booking> Bookings { get; set; }
}
}
And here is my DbContext. The error comes from the 25th Line ".HasMany(b => b.Persons)".
using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Diagnostics.CodeAnalysis;
using BookADesk.API.Models;
namespace BookADesk.API.Models
{
public class BookADeskContext : DbContext
{
public BookADeskContext(DbContextOptions options)
: base(options)
{
}
public DbSet<Booking> Booking { get; set; } = null!;
public DbSet<Desk> Desk { get; set; } = null!;
public DbSet<Location> Location { get; set; } = null!;
public DbSet<Person> Person { get; set; } = null!;
public DbSet<Room> Room { get; set; } = null!;
public DbSet<Zone> Zone { get; set; } = null!;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Booking>()
.HasMany(b => b.Persons)
.WithMany(p => p.Bookings);
}
}
}