so I want to create the relationships between my Model classes (Booking and Person). I found a tutorial for that
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);
}
}
}
CodePudding user response:
Person
has many Booking
s (ICollection<Booking> Bookings
) and Booking
has one Person
(Person Persons
).
Also Booking
has PersonId
which means that one booking can belong to/depend on only ONE Person
- this is the reason why .HasMany(b => b.Persons)
does not work.
To have many-to-many
relations Booking
should have ICollection<Person> Persons
(collection) (but as for me it doesn't make sense - how can one booking have many persons?).
So your mapping (one-to-many
) should be:
modelBuilder.Entity<Booking>()
.HasOne(b => b.Persons) // consider renaming to Person
.WithMany(p => p.Bookings)
.HasForeignKey(b => b.PersonId);
Or if you need many-to-many
you need to make changes in Booking
entity:
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 ICollection<Person> Persons { get; set; } // collection
// PersonId is not here anymore
}
And mapping (or you can go with your mapping):
modelBuilder.Entity<Person>()
.HasMany(p => p.Bookings)
.WithMany(b => b.Persons);