如何在虚拟字段中插入值
本文关键字:插入 字段 虚拟 | 更新日期: 2023-09-27 18:10:19
我有一个学习表,我设置值到一个用户注册,'注册(RegisterViewModel模型)'在AccountController。
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
using (The_FactoryDBContext db = new The_FactoryDBContext())
{
Learner learner = new Learner();
learner.learnerID = User.Identity.GetUserId();
learner.llCounter = 0;
learner.dtwCounter = 0;
learner.ftwCounter = 0;
learner.counter = 0;
db.Learners.Add(learner);
db.SaveChanges();
}
}
}
这是我的学习器自动生成类的一些虚拟字段的样子。
public partial class Learner
{
public Learner()
{
this.Learner_Treasure = new HashSet<Learner_Treasure>();
}
public string learnerID { get; set; }
public int llCounter { get; set; }
public int dtwCounter { get; set; }
public int ftwCounter { get; set; }
public int counter { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
public virtual ICollection<Learner_Treasure> Learner_Treasure { get; set; }
}
}
然而,我得到这个错误在注册,我不知道如何修复它,有人可以帮助我,或者是我的代码可能在错误的地方?
INSERT语句与外键约束FK_Learner_AspNetUsers1冲突。冲突发生在数据库"The_Factory",表"dbo"。"AspNetUsers",列"Id"
类
public partial class AspNetUser
{
public AspNetUser()
{
this.AspNetUserClaims = new HashSet<AspNetUserClaim>();
this.AspNetUserLogins = new HashSet<AspNetUserLogin>();
this.AspNetRoles = new HashSet<AspNetRole>();
}
public string Id { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string UserName { get; set; }
public int AvatarID { get; set; }
public virtual ICollection<AspNetUserClaim> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetUserLogin> AspNetUserLogins { get; set; }
public virtual Avatar Avatar { get; set; }
public virtual Learner Learner { get; set; }
public virtual ICollection<AspNetRole> AspNetRoles { get; set; }
}
}
Try with
[ForeignKey("AspNetUser")]
/learnerID
属性。原因是EF不知道您正在创建从learner
到user
的1-1映射(并且learner
中的PK也是到user
的FK)。设置这个属性可以告诉EF你的设计。