英文:
How does List work in EntityFramework Entity?
问题
我有2个数据模型:
public class Role
{
int Id;
string Name;
}
和
public class User
{
int Id;
string Name;
List<Role> Roles;
}
这是我的DbContext:
public class DatabaseContext : DbContext
{
public DbSet<User> Users => Set<User>();
public DbSet<Role> Roles => Set<Role>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=database.sqlite");
}
}
但是我在List<Role>
方面遇到了问题,当我从查看器中检查数据库数据时,我看到Users
表中没有任何用户的Roles
,但Roles
表中有UserID
属性,它似乎可以工作,但只存储一个ID,我该如何修复它?
我需要有多个角色和具有其中一些角色的用户。
英文:
I have 2 data models:
public class Role
{
int Id;
string Name;
}
and
public class User
{
int Id;
string Name;
List<Role> Roles;
}
there is my DbContext:
public class DatabaseContext : DbContext
{
public DbSet<User> Users => Set<User>();
public DbSet<Role> Roles => Set<Role>();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=database.sqlite");
}
}
but i have troubles with List<Role>
, when i check db data from viewer, i see that Users
table does not have any Roles
in users, but Roles
table has property UserID
, it kinda works but only 1 id stored there, how can i fix it?
I need to have multiple roles
and users that has some of these roles
答案1
得分: 0
> 它有点起作用,但只有一个ID被存储在那里,我该如何修复它?
这取决于你实际想要的。根据应用程序的要求,通常用户可以被分配一个角色,或者用户和角色之间存在多对多的关系。
如果你希望用户只能拥有一个角色,那么你应该反转关系,即角色具有用户列表:
public class Role
{
// ...
public List<User> Users { get; set; } = new();
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
对于多对多的情况,有两个主要选项 - 在双方都指定List
,并让EF内部创建联接表,或者显式配置联接表(EF Core关于多对多的文档)。对于第一种情况,你的实体可以如下所示:
public class Role
{
// ...
public List<User> Users { get; set; } = new();
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public List<Role> Roles { get; set; } = new();
}
英文:
> it kinda works but only 1 id stored there, how can I fix it?
It depends on what you actually want. Depending on the app requirements usually user can be assigned only one role or there is a many-to-many relationship between users and roles.
In case if you want user to have only one role then you should reverse the relationship i.e. role has list of users:
public class Role
{
// ...
public List<User> Users { get; set; } = new();
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
For the many-to-many case there are two main options - specify List
on both sides and let EF internally create the join table or explicitly configure the join table (EF Core docs on many-to-many). For the first case your entities can look like the following:
public class Role
{
// ...
public List<User> Users { get; set; } = new();
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public List<Role> Roles { get; set; } = new();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论