I am struggling to setup a scenario (using C# classes and OnModelCreating()
method) where DB models would act as follows:
First assumption, the mandatory one:
I want to have the ability to create
User
(AspNetUsers
table) without a reference to aGuest
. It will be necessary while seeding a DB with anadmin
user - it will not belong to any of theEvent
-s. In summary - at least that's my understanding -User
will be PRINCIPAL,Guest
will be DEPENDENT (?)Cascading deletion: I want to delete Users from AspNetUsers table when I delete a given Event (cascade delete). This functionality already exists for
Guests
. When I delete anEvent
, all relatedGuests
are being deleted correctly.
Two questions:
1. How do I actually create Guests that are related to AspNetUsers
table?
When it comes to Guests
list and its assignement to a ceratin Event, I just do something like:
eventDbObject.Guests = GetGuestsList();
_dbContext.Events.Add(evenDbObject); //Event is created in Events table, Guests table is correctly populated as well
With users it's tricky - I have to Register them first, get their ID, and then assign that ID to a Guest
object. Is that way correct?
foreach (var guest in weddingDbObject.Guests)
{
var userCreationResult = await _identityService.RegisterAsync("userName","password"); // my RegisterAsync() method returns actual User
guest.AppUser = userCreationResult.User;
}
2. How to set up cascade deletion in such a scenario?
builder
.Entity<Guest>()
.HasOne(e => e.AppUser)
.WithOne(e => e.Guest)
.OnDelete(DeleteBehavior.Cascade);
Something like this does not seem to work
My classes:
public class Event
{
// PK
public Guid Id {get;set;}
public List<Guest> Guests { get; set; }
}
public class Guest
{
// PK
public Guid Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public Guid AppUserId { get; set; }
public AppUser AppUser { get; set; }
}
public class AppUser : IdentityUser<Guid>
{
public WeddingGuest Guest { get; set; }
}