EF 6.1.3 - Cannot insert duplicate key in object

asp.net entity-framework entity-framework-6

Question

I looked online for a solution to my issue, but I haven't found one. I have two things.

public class Article
{
    [Key]
    public Guid ID { get; set; }
    public Guid? ApprovedBy_ID { get; set; }
    public Guid CreatedBy_ID { get; set; }
    public virtual Profile ApprovedBy { get; set; }
    public virtual Profile CreatedBy { get; set; }
    //New guid for new article
    public Article()
    {
        ID = Guid.NewGuid();
    }
}
public class Profile
{
    [Key]
    public Guid ID { get; set; }
    [Required]
    [StringLength(100)]
    public string FullName { get; set; }
    public Profile()
    {
        ID = Guid.NewGuid();
    }
}

Here is my logic behind the insert:

    private readonly iContext context;
    public ArticleLogic()
    {
        context = new iContext();
    }
    public IEnumerable<Article> GetAllArticle()
    {
        return context.Articles.Include("Categories").Include("Pictures").Include("ApprovedBy").Include("CreatedBy").Include("Template");
    }

    public Article AddArticle(Article article)
    {
            try
            {
                Profile pf = context.Profiles.First();
                context.Profiles.Attach(pf);

                Article art = new Article();
                art.Title = article.Title;
                art.Description = article.Description;
                art.Content = article.Content;
                art.Tag = article.Tag;
                art.Template = article.Template;
                //pf has ID = '0816f19c-31c1-4103-8f51-ba422beab1c0' (first row in database)
                art.CreatedBy = pf;
                art.CreatedBy_ID = pf.ID;
                context.Articles.Add(art);
                context.SaveChanges();

                return article;
            }
            catch (Exception ex)
            {
                //But ex throw error duplicate ID = '7aa1d064-54ff-47b9-807d-db422fa71f8c' (second row in database)
                Debug.WriteLine(ex.StackTrace);

                throw ex;
            }

    }

The DB Context

public myContext()
    : base("name=abc")
{
    this.Configuration.LazyLoadingEnabled = true;
    this.Configuration.ProxyCreationEnabled = false;
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Role> Roles { get; set; }
public virtual DbSet<Template> Templates { get; set; }
public virtual DbSet<Article> Articles { get; set; }
public virtual DbSet<Picture> Pictures { get; set; }
public virtual DbSet<Profile> Profiles { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //One-to-many: Article - Picture (nullable)
    modelBuilder.Entity<Picture>()
        .HasOptional<Article>(c => c.Article)
        .WithMany(p => p.Pictures)
        .HasForeignKey(f => f.ArticleId);

    ////One-to-many: Role - Profile
    modelBuilder.Entity<Profile>()
        .HasRequired<Role>(i => i.Role)
        .WithMany(i => i.Profiles)
        .HasForeignKey(f => f.RoleID);

    ///Many-to-many: Article - Category
    modelBuilder.Entity<Article>()
        .HasMany(t => t.Categories)
        .WithMany(t => t.Articles)
        .Map(m => {
                m.ToTable("ArticleCategories");
                m.MapLeftKey("ArticleId");
                m.MapRightKey("CategoryId");
         });
    //
        modelBuilder.Entity<Article>()
            .HasOptional(a => a.ApprovedBy)
            .WithMany(a => a.ArticleApprovedBy)
            .HasForeignKey(f=>f.ApprovedBy_ID)
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<Article>()
            .HasRequired(a => a.CreatedBy)
            .WithMany(a => a.ArticleCreatedBy)
            .HasForeignKey(f => f.CreatedBy_ID)
            .WillCascadeOnDelete(false);

        base.OnModelCreating(modelBuilder);
}

The error message I receive when using CodeFirst EF 6.1.3 is: Violation of PRIMARY KEY constraint "PK Profiles". Cannot insert a duplicate key like this link Cannot insert duplicate key in object "dbo.T CRProviders" in Entity Framework Code First in the object "dbo.Profiles" Can somebody assist me? Thanks.

1
0
5/23/2017 11:51:57 AM

Popular Answer

In your line

 context.Profiles.Attach(pf);

will attach the pf, but EF has already located it. It was simply pulled from the database. EF will attempt to re-insert the fp, but this fails. You will be OK if you simply remove the line.

Entity States and Add/Attach

0
10/29/2015 7:17:55 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow