gpt4 book ai didi

c# - Entity Framework 无法在对象中插入重复键

转载 作者:行者123 更新时间:2023-11-30 20:46:29 26 4
gpt4 key购买 nike

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

我在 Entity Framework 代码中首先有一对多的关系:

[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 尝试创建用户时,出现异常:

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."

OnModelCreating 我有这段代码:

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

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

最佳答案

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

我删除了 PricingPlan = pp,如 markpsmith 所说。然后,当我想获取带有附加实体定价计划的 UserProfile 时, 我只是让包括:

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

但是无法理解,为什么默认不包含,当 LazyLoading 设置为 false 时。

关于c# - Entity Framework 无法在对象中插入重复键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26842525/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com