Entity Framework Cannot insert duplicate key in object

asp.net-mvc asp.net-mvc-5 asp.net-web-api c# entity-framework-6


I am unable to solve my problem. I apologize if I repeated the question.

I have a first-one-to-many relationship in my Entity Framework code.

[DataContract(IsReference = true)]
public class PricingPlan

    public PricingPlan()
        UserProfiles = new List<UserProfile>();

    public Guid PricingPlanId { get; set; }

    public string Type { get; set; }

    public ICollection<UserProfile> UserProfiles { get; set; }

[DataContract(IsReference = true)]
public class UserProfile : IdentityUser
    public DateTime JoinedOn { get; set; }
    public DateTime LastVisited { get; set; }
    public string Location { get; set; }

    public Guid PricingPlanId { get; set; }
    public PricingPlan PricingPlan { get; set; }

I have two rows in the PricingPlan Table: Free and Pro.

I want to add the person who registers to the free plan:

    public async Task<IHttpActionResult> Register(RegisterBindingModel model)
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        PricingPlan pp = UnitOfwork.PricingPlanRepository.FirstOrDefault(v => v.Type == "Free");

        UserProfile user = new UserProfile
            UserName = model.UserName,
            Email = model.Email,
            EmailConfirmed = false,
            Location = model.Location,
            JoinedOn = DateTime.Now,
            LastVisited = DateTime.Now,
            PricingPlanId = pp.PricingPlanId,
            PricingPlan = pp

        IdentityResult identityResult = await UserManager.CreateAsync(user, model.Password);

I'm pulling an already-existing plan from the database and putting it to the userProfile property, however when UserManager attempts to create a user, I receive the following exception:

Violation of PRIMARY KEY constraint 'PK_dbo.PricingPlans'. Cannot insert duplicate key in object 'dbo.PricingPlans'. The duplicate key value is (a5139db8-64c1-49a2-97ef-55009259dc23).\r\nThe statement has been terminated."

This is the code I have for onModelCreating:

  modelBuilder.Entity<UserProfile>().HasRequired<PricingPlan>(r=>r.PricingPlan).WithMany(c => c.UserProfiles).HasForeignKey(a=>a.PricingPlanId);

What should the first step be when adding an existing entity to a new entity in a one-to-many relation?

11/10/2014 11:28:18 AM

Accepted Answer

Okay, I've found a solution.

I deletedPricingPlan = pp likewise what markpsmith stated Then, I simply make Include: when I want to retrieve UserProfile with connected entity Pricingplan in it.


However, I don't know why it's not included by default whenLazyLoading is set to false.

1/29/2018 11:18:20 AM

Related Questions


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