将复杂类型类作为属性添加到 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; }
}

这不能通过仅使用

userclass
作为属性来完成吗?我不想创建它的 id,因为稍后可能会在 id 中发生冲突(重复项目等)

userclass
只有 3 个项目,所以我不想为此创建一个新的数据库集。

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.