找不到解决我问题的方法。很抱歉,如果我重复该问题。
我在实体框架代码中有一对多的关系:
[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尝试创建用户时,出现异常:
违反主键约束'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时,
我只包括:
this.Context.Set<UserProfile>().Include("PricingPlan").
但是不明白,为什么默认不包含它,
当
LazyLoading is set to false.
关于c# - Entity Framework 无法在对象中插入重复键,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26842525/