亲爱的SO成员请帮助我解开我认为应该是一项轻松的任务,但我已经被困了2天。我有几个表需要有一个FK到当前登录用户的UserId。这是一个例子
用户配置
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string ManagerName { get; set; }
public string PhoneNumber { get; set; }
}
客户实体
public class Customer
{
[Key]
public int CustomerId { get; set; }
public string Names { get; set; }
[ForeignKey("UserProfile")]
public int UserId { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
数据库上下文
public class UsersContext : DbContext
{
public UsersContext()
: base("DefaultConnection")
{
}
public DbSet<UserProfile> UserProfiles { get; set; }
public DbSet<Customer> Customers { get; set; }
}
客户控制器
[HttpPost]
[InitializeSimpleMembership]
[ValidateAntiForgeryToken]
public ActionResult Create(Customer model)
{
if (ModelState.IsValid)
{
model.UserProfile = db.UserProfiles.FirstOrDefault(u => u.UserId == WebSecurity.CurrentUserId);
db.Customers.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.UserProfiles, "UserId", "UserName", model.UserId);
return View(model);
}
也试过
[HttpPost]
[InitializeSimpleMembership]
[ValidateAntiForgeryToken]
public ActionResult Create(Customer model)
{
if (ModelState.IsValid)
{
model.UserId = WebSecurity.GetUserId(User.Identity.Name);
db.Customers.Add(model);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.UserId = new SelectList(db.UserProfiles, "UserId", "UserName", model.UserId);
return View(model);
}
在每种情况下,我都会收到错误消息
"The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Customers_dbo.UserProfile_UserId". The conflict occurred in database "ValueCardProject", table "dbo.UserProfile", column 'UserId'.
The statement has been terminated."
我想要做的就是能够使用FK创建表到登录用户的UserID。为了完全披露的利益,客户不应该直接创建为用户,在我的用例中,当前登录的用户是零售商,所以我想要完成的是用FK创建一个客户记录到RetailerId(这是UserProfile中的UserId。)
感谢您的时间。
答案 0 :(得分:0)
我相信UserId上的外键属性位置错误。
你应该这样做:
public int UserId { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile UserProfile { get; set; }