我现在正在失去理智。我正在尝试使用存在于子身份和父身份上的导航属性对数据库模型进行建模。这意味着,父级具有指向子级的nav属性,而子级具有指向父级的nav属性。
这是我的模特:
public class User : IdentityUser
{
public Company Company { get; set; }
public Employee Employee { get; set; }
}
public class Employee
{
[Key]
public int ID { get; set; }
public Address Address { get; set; }
public User Account { get; set; }
}
public class Company
{
[Key]
public int ID { get; set; }
public List<User> Accounts { get; set; }
}
public class Address
{
[Key]
public int ID { get; set; }
public Employee Employee { get; set; }
}
然后我创建了一个数据库上下文类,如下所示:
public class UserManagementDbContext : IdentityDbContext<User>
{
public DbSet<Company> Companies { get; set; }
public DbSet<Employee> Employees { get; set; }
public DbSet<Address> Addresses { get; set; }
public UserManagementDbContext(DbContextOptions<UserManagementDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<User>()
.OwnsOne(cu => cu.Employee)
.HasOne(e => e.Account);
builder.Entity<User>()
.HasOne(cu => cu.Company)
.WithMany(c => c.Accounts);
builder.Entity<Employee>()
.OwnsOne(e => e.Address)
.HasOne(a => a.Employee);
builder.Entity<User>().ToTable("Accounts");
builder.Entity<IdentityRole>().ToTable("Roles");
}
}
然后我像这样在Startup.cs中调用数据库的SecureCreated()方法:
private async Task InitializeDatabase(IServiceProvider serviceProvider)
{
using (var serviceScope = serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
using (var db = serviceProvider.GetService<UserManagementDbContext>())
{
db.Database.EnsureCreated();
//...omitted
}
}
}
这是应用程序因上述错误而失败的地方,我不明白为什么。帐户和地址表之间没有关系。我要么是蝙蝠瞎子,没有注意到错字,要么这个错误确实令人困惑。
有人可以帮我吗?
编辑:请注意,我不想使用外键,而只是导航属性。