【问题标题】:How to add one to one mapping between entities如何在实体之间添加一对一映射
【发布时间】:2015-11-17 12:15:31
【问题描述】:

我正在尝试使用实体框架创建“注册新用户”功能。每个新用户应该在 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;
    }
}

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

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

我得到异常

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

所以我有两个问题

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

【问题讨论】:

  • 您使用HasOptional1:1 映射相矛盾,它暗示0..1:1,这是完全不同的。你能告诉我们你的意思是0..1:1还是1:1
  • 你的问题解决了吗?
  • @Daniel 还没有。 UserProfileId 作为身份列正在产生问题

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


【解决方案1】:

对于您的一对一映射和 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-25
    • 2021-11-11
    相关资源
    最近更新 更多