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

本文关键字:插入 对象 框架 实体 | 更新日期: 2023-09-27 18:29:47

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

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

[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表中,我有两行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);

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

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

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

我删除了PricingPlan = pp,就像markpsmith说的那样。然后,当我想获得带有附加实体Pricingplan的UserProfile时,我只是做Include:

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

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