【发布时间】:2022-01-21 15:33:19
【问题描述】:
您好,我正在尝试使用我的 Asp.Net MVC 项目在我的实体 Entreprise 中添加一个 ApplicationUser(来自 IdentityUser 的派生类)。它们之间有多对多的关系,而且自从我的数据库中的表 ApplicationUserEntreprise 得到更新后,它似乎可以工作。但是当我尝试做类似 user.Entreprisew 或 entreprise.Users 的事情时,它总是返回 null
这是我的 EntrepriseRepo 的 addUser 方法,我尝试在其中建立实体之间的链接
public void AddUser(ApplicationUser user , Entreprise entreprise) {
Entreprise entrepriseFromDb = base.FirstOrDefaultAsync(u => u.Id == entreprise.Id).Result;
if (entrepriseFromDb.ApplicationUsers == null)
{
entrepriseFromDb.ApplicationUsers = new List<ApplicationUser>();
entrepriseFromDb.ApplicationUsers.Add(user);
}
else {
entrepriseFromDb.ApplicationUsers.Add(user);
}
if (user.Entreprises == null) {
user.Entreprises = new List<Entreprise>();
user.Entreprises.Add(entrepriseFromDb);
}
else
{
user.Entreprises.Add(entrepriseFromDb);
}
}
我的控制器
public async Task AddUser(int id, string UserId)
{
Entreprise entreprise = await _services.Configuration.GetEntreprise(id);
ApplicationUser user = await _userManager.FindByIdAsync(UserId);
_services.Configuration.AddUserToEntrepriseAsync(user, entreprise);
await Details(id);
}
我的服务
public void AddUserToEntrepriseAsync(ApplicationUser user, Entreprise entreprise) {
_uow.Entreprises.AddUser(user, entreprise);
_uow.Save();
}
这是我的课程
应用用户
public class ApplicationUser : IdentityUser
{
public ICollection<Entreprise> Entreprises { get; set; }
}
企业
public class Entreprise
{
public int Id { get; set; }
public string Nom { get; set; }
public string LogoURL { get; set; }
public List<Groupe> Groupes { get; set; }
public List<Periode> Periodes { get; set; }
[NotMapped]
public int GroupesCount { get; set; }
[NotMapped]
public int EquipementsCount { get; set; }
[NotMapped]
public int PeriodesCount { get; set; }
public ICollection<ApplicationUser> ApplicationUsers{ get; set; }
}
有什么方法可以通过 entreprise.User 获取我的用户列表,通过 user.Entreprises 获取我的企业列表?
【问题讨论】:
-
刚刚意识到我可以使用参数 includeProperties 在我的 addUser 方法中访问 entreprise.Users。像这样:base.FirstOrDefaultAsync(u => u.Id == entreprise.Id, includeProperties: "ApplicationUsers").Result;。但我仍然想知道如何使用 user.Entreprises 访问我的用户的企业列表
标签: c# entity-framework asp.net-identity many-to-many repository-pattern