0

亲爱的 SO 成员,请帮助我摆脱我认为应该是一件容易的任务,但我已经被困了 2 天。我有几个表需要对当前登录用户的 UserId 进行 FK。这是一个例子

用户资料

    [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)。

谢谢你的时间。

4

1 回答 1

0

我相信您在 UserId 上的外键属性位于错误的位置。

你应该这样做:

public int UserId { get; set; }

[ForeignKey("UserId")]
public virtual UserProfile UserProfile { get; set; }
于 2013-12-10T19:55:57.713 回答