如何在实体之间添加一对一映射

时间:2015-11-17 12:15:32

标签: c# entity-framework ef-code-first code-first ef-fluent-api

我正在尝试使用实体框架工作创建“注册新用户”功能。每个新用户应在UserAccount表中有一个条目,在UserProfile中有一个条目。两者都由外键列UserAccountId链接。每个新用户配置文件都可以由现有管理员批准,因此我在UserProfile表中有一个ApprovedById db列(可为空)

这是我迄今为止所做的。

public class UserAccount
{
    [Key] //This is primary key
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserAccountId { get; set; }

    [StringLength(320)]
    public String LoginEmail { get; set; }

    [StringLength(128)]
    public String Password { get; set; }

    [Column("PasswordExpired")]
    public Boolean HasPasswordExpired { get; set; }

    public virtual UserProfile UserProfile { get; set; }
}   

public class UserProfile
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserProfileId { get; set; }

    [StringLength(320)]
    public String SecondaryEmail { get; set; }

    [StringLength(100)]
    public String DisplayName { get; set; }

    public int UserAccountId { get; set; }
    public virtual UserAccount UserAccount { get; set; }

    public int? ApprovedById { get; set; }
    public virtual UserAccount ApprovedBy { get; set; }

    public DateTime? ApprovedDate { get; set; }

}

public class AccountsDataContext : BaseDataContext<AccountsDataContext> // BaseDataContext has something to get connectionstring etc.
{
    public DbSet<UserAccount> UserAccounts { get; set; }
    public DbSet<UserProfile> UserProfiles { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserAccount>()
                    .HasOptional(a => a.UserProfile)
                    .WithRequired(p => p.UserAccount);
        //I also want to add constraint for ApprovedByAccount here but if I do that it gives me circular dependency error
    }
}

public class AccountsModel
{
    /// <summary>
    /// Password in userAccount will be encrypted before saving.
    /// </summary>
    public bool CreateNewUser(String primaryEmail, String password, String displayName, out String error)
    {
        using (AccountsDataContext context = new AccountsDataContext())
        {
            UserAccount account = new UserAccount { LoginEmail = primaryEmail };
            UserProfile profile = new UserProfile { DisplayName = displayName };
            if (!context.UserAccounts.Any(a => String.Equals(primaryEmail, a.LoginEmail)))
            {
                if (profile != null)
                    account.UserProfile = profile;
                account.Password = GetHashString(password);
                context.UserAccounts.Add(account);
                context.SaveChanges();
                error = null;
                return true;
            }
        }
        error = "Some error";
        return false;
    }
}

当我按照以下方式调用最后一个Model方法时

        AccountsModel model = new AccountsModel();
        string error;
        model.CreateNewUser("my@email.com", "password", "The Guy in Problem", out error);

我得到例外

  

ReferentialConstraint中的依赖属性映射到存储生成的列。专栏:'UserProfileId'。

所以我有两个问题

  1. 如何在帐户和个人资料
  2. 之间添加一对一的映射
  3. 如何为ApprovedBy添加约束

1 个答案:

答案 0 :(得分:0)

对于您的一对一映射和ApprouvedBy的关系,您可以这样做

public class UserProfile
{
    [Key, ForeignKey("UserAccount")]
    public int UserProfileId { get; set; }

    public UserAccount UserAccount{ get; set; }

    [ForeignKey("ApprovedBy")]
    public int? ApprovedById { get; set; }
    public virtual UserAccount ApprovedBy { get; set; }
}

您可以删除UserProfile中的UserAccount