实体框架无法在对象中插入重复键

时间:2014-11-10 11:15:19

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

找不到我的问题的解决方案。对不起,如果我复制了这个问题。

我在实体框架代码中首先与一对多有关系:

[DataContract(IsReference = true)]
public class PricingPlan
{

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

    [Key]
    [DataMember]
    public Guid PricingPlanId { get; set; }

    [DataMember]
    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; }
}

在PricingPlan表中,我有2行Free和Pro

用户注册时,我想将他添加到免费计划中:

    [AllowAnonymous]
    [Route("Register")]
    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);

我从Db获取现有计划并将其添加到userProfile属性,但是当UserManager尝试创建用户时,我得到例外:

  

违反PRIMARY KEY约束'PK_dbo.PricingPlans'。不能   在对象'dbo.PricingPlans'中插入重复键。重复的密钥   值是(a5139db8-64c1-49a2-97ef-55009259dc23)。\ r \ n声明有   已被终止。“

OnModelCreating我有这段代码:

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

首先在实体框架代码中以一对多关系将新实体添加到新实体的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

好的,我解决了这个问题。

我删除了PricingPlan = pp,就像markpsmith说的那样。然后,当我想在其中添加附加实体Pricingplan的UserProfile时,  我只是做包括:

this.Context.Set<UserProfile>().Include("PricingPlan").

但无法理解,为什么默认不包含它, 何时LazyLoading is set to false.