我有以下表格:User,UserGroups和UserInGroups。你可以在下面的圖片上看到它們。當我打電話用戶時,我希望能夠獲取用戶所在的組(UserInGroups)。我正在閱讀有關EntityFramework的資料,但我無法在代碼中建立連接,因此我錯過了什麼?我需要在模型創建上連接它們嗎?EntityFramework代碼第一鍵
目前我沒有從UserInGroup或UserGroups獲取任何數據。
我的課是這樣的:
public class User : BaseEntity
{
public int RoleId { get; set; }
public Role Role { get; set; }
public UserGroup UserGroup { get; set; }
public UserInGroup UserInGroup { get; set; }
}
public class UserGroup : BaseEntity
{
public UserGroup()
{
Users = new List<User>();
UserInGroups = new List<UserInGroup>();
}
[StringLength(255)]
public string Name { get; set; }
public string KeyName { get; set; }
public List<User> Users { get; set; }
public List<UserInGroup> UserInGroups { get; set; }
}
public class UserInGroup : BaseEntity
{
public UserInGroup()
{
Users = new List<User>();
UserGroups = new List<UserGroup>();
}
public int UserId { get; set; }
public User User { get; set; }
public int UserGroupId { get; set; }
public UserGroup UserGroup { get; set; }
public List<User> Users { get; set; }
public List<UserGroup> UserGroups { get; set; }
}
的DbContext:
public DbSet<GlobalSettings> GlobalSettings { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserGroup> UserGroups { get; set; }
public DbSet<UserInGroup> UsersInGroups { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<GlobalSettings>().Property(x => x.Key).HasColumnAnnotation("Index", new IndexAnnotation(new[] { new IndexAttribute("Index_VariablenName") { IsClustered = false, IsUnique = true } }));
}
你的情況在哪裏?和你的映射? – DevilSuichiro
你不應該在UserGroup中有'List Users',你不應該在UserInGroup中擁有集合。如果我很好地展現你的模型,用戶只能通過UserInGroup加入一個組。 –
tschmit007
我已將DB上下文添加到頂端帖子。我創建的數據庫沒有問題,UserInGroups確實擁有用戶和組表的外鍵。只有我面臨的問題是我不知道如何獲取代碼中的數據。 @ tschmit007是用戶只能在UserInGroup中加入組 我從User和UserGroup中刪除了列表 –