I have the two table like this:
public class NotificationType : AuditableEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }
public string Channel { get; set; }
}
public class NotificationSubscription : AuditableEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id { get; set; }
public string UserId { get; set; }
public string NotificationTypeId { get; set; }
public NotificationType NotificationTypes { get; private set; } = new();
}
When I am seeding the data I am doing like this:
context.NotificationTypes.Add(new NotificationType
{
Id = "4C1B3788-3CDE-4F6D-82EB-7B4B71A601EF",
Channel = "Email",
});
await context.SaveChangesAsync();
context.NotificationSubscriptions.Add(new NotificationSubscription
{
Id = "5A4944C7-9FD8-4BC3-81F7-2ED92729962B",
UserId = "081C459B-77D3-45F3-B26A-6879EAE53FC2",
NotificationTypeId = "4C1B3788-3CDE-4F6D-82EB-7B4B71A601EF",
});
await context.SaveChangesAsync();
DbContext
public DbSet<NotificationType> NotificationTypes { get; set; }
public DbSet<NotificationSubscription> NotificationSubscriptions { get; set; }
public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
foreach (Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<AuditableEntity> entry in ChangeTracker.Entries<AuditableEntity>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedBy = _currentUserService.UserId;
entry.Entity.Created = _dateTime.Now;
break;
case EntityState.Modified:
entry.Entity.LastModifiedBy = _currentUserService.UserId;
entry.Entity.LastModified = _dateTime.Now;
break;
}
}
var result = await base.SaveChangesAsync(cancellationToken);
return result;
}
The NotificationTypes
get saved without any problem, but while trying to save to the NotificationSubscriptions
, got the error:
Unable to track an entity of type 'NotificationType' because its primary key property 'Id' is null.
I guess the issue is due to the mapping from the one-to-one relationships. But I don't know how to exactly solve the issues. I don't want to add NotificationType while adding the NotificationTypes, I just want to reference it with the NotificationTypeId.
Please guide me with the workaround or the possible solution.