我在具有EF Core和Identity的Asp.NET Core 3.1 MVC中有一个应用程序。
我有两个表Calls
和AspNetUsers
。 AspNetUsers
有很多Calls
,一个Call
有一个AspNetUsers
。
我认为Calls
表结构还可以。但是现在我需要从Calls
中获取AspNetUsers
。
在CallsController
中,我正在尝试:IList<Call> calls = this.User.Calls;
,但没有成功。
我尝试过:
IList<Call> calls = this._context.Calls.Where(x => x.UserId == this._userManager.GetUserId(this.User)).ToList();
我成功。但这是正确的吗?
因此,在应用程序中,我具有标识类和一个像这样的ApplicationUser
:
public class ApplicationUser : IdentityUser
{
public virtual IList<Call> Calls { get; set; }
}
并且在Startup
方法的ConfigureServices
类中:
services.AddDefaultIdentity<ApplicationUser>(options =>
options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
因此,从AspNetUsers获得呼叫的更好方法是什么? 谢谢!
您可以像设置ApplicationUser
:
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Call> Calls { get; set; }
}
Call.cs:
public class Call
{
public int ID { get; set; }
public string name { get; set; }
// other properties
public string UserID { get; set; }
[ForeignKey("UserID")]
public virtual ApplicationUser ApplicationUser { get; set; }
}
在ApplicationDbContext中,添加:
public virtual DbSet<Call> Calls { get; set; } //add this line
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
然后您可以通过以下方式查询当前用户的呼叫:
if (User.Identity.IsAuthenticated)
{
var userID = User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
var calls = _applicationDbContext.Users.Include(u => u.Calls).First(u => u.Id == userID).Calls.ToList();
//or
var callsa = _applicationDbContext.Calls.Where(p => p.UserID == userID).ToList();
}