c# - 为什么 HasRequired 不起作用?

标签 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);
    }
}

最佳答案

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

    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 是一对一的映射。

关于c# - 为什么 HasRequired 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21910390/

相关文章:

java - 如何将鱼尾纹添加到 UMLet?

php - Symfony2 - 通知 : Undefined offset: 0 due to a custom Query

c# - 在 try,catch block 之外运行代码是否有任何性能优势?

c# - 使用 AuthorizeAttribute 进行 MVC 集成测试

c# - 使用 EF 查询数据不会返回所有实体

visual-studio-2010 - 被 "The EntityCollection has already been initialized."错误卡住

c# - ASP.NET Identity UserManager IIdentityMessageService 将额外参数传递给 SendAsync

c# - 将 LINQ to SQL 中的多个复杂 WHERE 子句链接在一起

c# - 调用存储过程的 Entity Framework 需要未提供的参数

MySQL加入?这些是什么?什么时候使用它们?