I am new to Blazor and right now I trying to create models with one to many relationship. I have model classes Project
and ProjectCategory
:
public class Project{ public Guid Id { get; set; } public string? Title { get; set; } public string? Description { get; set; } public string? FileUrl { get; set; } public virtual ProjectCategory ProjectCategory { get; set; } public string? GithubLink { get; set; }}public class ProjectCategory{ public Guid Id { get; set; } public string? Title { get; set; } public virtual ICollection<Project> Projects { get; set; } = new ObservableCollection<Project>();}
This is my DbContext
file:
public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : IdentityDbContext<ApplicationUser>(options){ protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<ProjectCategory>().HasMany(c => c.Projects).WithOne(c => c.ProjectCategory).HasForeignKey(c => c.Id).IsRequired(); base.OnModelCreating(builder); } public DbSet<Project> Projects { get; set; } public DbSet<ProjectCategory> ProjectCategories { get; set; }}
This is my create project code:
var pc = await _projectDataContext.ProjectCategories.FindAsync(Input.ProjectCategory);pc.Projects.Add(NewProject);await _projectDataContext.SaveChangesAsync();await _projectDataContext.DisposeAsync();
Yet when I try to create a project, i get a Violation of PRIMARY KEY constraint 'PK_Projects'. Cannot insert duplicate key in object 'dbo.Projects'
error. What am I doing wrong? Thank you.