gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:27:26 26 4
gpt4 key购买 nike

我试图在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com