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

本文关键字:添加 一对一 映射 之间 实体 | 更新日期: 2023-09-27 18:22:17

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

这就是我迄今为止所做的。

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;
    }
}

当我以以下方式调用模型的最后一个方法时

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

我作为获得异常

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

所以我有两个问题

  1. 如何在Account和Profile之间添加一对一映射
  2. 如何为ApprovedBy添加约束

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

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

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; }
}

并且您可以删除UserAccount中的UserProfile