C# MVC 4 UserProfile外键/不允许nulls错误

C# MVC 4 UserProfile外键/不允许nulls错误,c#,asp.net-mvc,entity-framework,asp.net-mvc-4,C#,Asp.net Mvc,Entity Framework,Asp.net Mvc 4,我使用与MVC4身份验证方法相关的实体框架。我创建了一个自定义的UserProfile,以包含一些其他表 UserProfile [Table("UserProfile")] public class UserProfile { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int UserId { get; set; } public string UserName { ge

我使用与MVC4身份验证方法相关的实体框架。我创建了一个自定义的
UserProfile
,以包含一些其他表

UserProfile

[Table("UserProfile")]
public class UserProfile
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string UserName { get; set; }

    public int CompanyId { get; set; }

    [ForeignKey("CompanyId")]
    public virtual Company Company { get; set; }
}
公司

public class Company
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
}
现在
WebSecurity.CreateUserAndAccount(“MyUser”、“MyPassword”)引发以下异常:

无法将值NULL插入表“aspnet.web-67.dbo.UserProfile”的列“CompanyId”;列不允许空值。插入失败。该语句已终止。

我可以删除ForeignKey,但在此之后,延迟加载似乎不再有效。

我认为UserProfile表的CompanyId列是在DB中创建的不允许空值。你可以这样写

公共int?CompanyId{get;set;}


或者您必须在创建用户之前添加CompanyId值

付款是公司吗?我不明白。你也可以写为
int?
Nullable
看起来有点过时。是谁建议的?这是我个人的偏好,我只是指出了这一点。