Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4334

ASP.NET Blazor : cannot insert duplicate key in object when creating one-to-many relationship

$
0
0

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.


Viewing all articles
Browse latest Browse all 4334

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>