在 EF 中添加复杂类型类作为模型属性时,类需要定义主键

问题描述 投票:0回答:1

我想使用一个对象作为我的实体/模型的属性 我不希望它有自己的桌子或其他东西

[ComplexType]
public class userclass
{
    public bool client { get; set; }
    public bool admin { get; set; }
    public bool superAdmin { get; set; }
}
public class user : IdentityUser<int>
{
    [Key]
    public int Id { get; set; }
     public userclass? Role { get; set; }
}

不能仅使用用户类作为属性来完成此操作,我不想创建它的 id,因为稍后可能会在 id 中发生冲突(重复项目等) userclass 只有 3 个项目,所以我不想创建新的 dbset

c# entity-framework asp.net-core
1个回答
0
投票

如果我理解得很好,您希望将用户类内容与用户放在同一个表中吗? 如果是这种情况,在定义 dbContext 时,您可以像这样覆盖 OnModelCreating:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{  
  //...
 modelBuilder.Entity<user >()
   .OwnsOne(x => x.userclass);
//...
 

}

© www.soinside.com 2019 - 2024. All rights reserved.