为什么HasRequired不起作用?

时间:2014-02-20 14:14:50

标签: c# entity-framework entity-relationship

我正在尝试在User表和UserSettings表之间建立一对一的关系。

尽管指定了'HasRequired'关系,我仍然能够插入没有任何设置的用户。我哪里错了?

public class ApplicationUser : IdentityUser
{
    public ApplicationUser()
    {
        // Settings = new UserSettings();
    }

    public string EmailAddress { get; set; }

    public virtual UserSettings Settings { get; set; }
}

public class UserSettings
{
    [Key]
    public string ApplicationUserId { get; set; }

    public virtual ApplicationUser ApplicationUser { get; set; }
}


public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
    : base("DefaultConnection")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ApplicationUser>().HasRequired(t => t.Settings).WithRequiredPrincipal(t => t.User);
    }
}

1 个答案:

答案 0 :(得分:1)

看到关系。 这是完整的工作代码:

    public class ApplicationUser 
        {
            public ApplicationUser()
            {
                // Settings = new UserSettings();
            }
                [Key]
            public string Id { get; set; }  //could be from the base class
            public string EmailAddress { get; set; }

            public virtual UserSettings Settings { get; set; }
        }

        public class UserSettings
        {
            [Key]
            public string ApplicationUserId { get; set; }

            public virtual ApplicationUser ApplicationUser { get; set; }
        }

     public class Context : DbContext
            { 
              protected override void OnModelCreating(DbModelBuilder modelBuilder)
                {
                    base.OnModelCreating(modelBuilder);

                    modelBuilder.Entity<UserSettings>()
                                     .HasRequired(t => t.ApplicationUser)
                                     .WithRequiredPrincipal(t => t.Settings);

                }
        }

我希望这有帮助... ApplicationUser有一个外键..在这种情况下,是一对一的UserSetting地图。