Asp.net mvc 4 ASP.Net MVC 4 SimpleMembership用户ID作为外键

Asp.net mvc 4 ASP.Net MVC 4 SimpleMembership用户ID作为外键,asp.net-mvc-4,entity-framework-5,simplemembership,Asp.net Mvc 4,Entity Framework 5,Simplemembership,亲爱的成员们,请帮助我在我认为应该是一项简单的任务中脱身,但我已经被困了2天。我有几个表需要对当前登录用户的UserId使用FK。这里有一个例子 用户配置文件 [Table("UserProfile")] public class UserProfile { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int User

亲爱的成员们,请帮助我在我认为应该是一项简单的任务中脱身,但我已经被困了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.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的表,该表指向登录用户的用户ID。为了充分披露,不应直接将客户创建为用户,在我的用例中,当前登录的用户是零售商,因此我尝试使用FK to RetailerId(用户配置文件中的用户ID)创建客户记录


谢谢您的时间。

我认为您在UserId上的外键属性放错了位置

您应该这样做:

public int UserId { get; set; }

[ForeignKey("UserId")]
public virtual UserProfile UserProfile { get; set; }

因为您正在尝试添加相同的用户
GetUserId
将返回已经存在的用户的信息,然后您将使用该
Id
创建具有相同
Id
的新用户,用户当前是否登录到系统?WebSecurity.CurrentUserId返回什么值?它是否与UserProfile表中的条目匹配?
public int UserId { get; set; }

[ForeignKey("UserId")]
public virtual UserProfile UserProfile { get; set; }