Identity User FK

问题描述 投票:0回答:1

我在具有EF Core和Identity的Asp.NET Core 3.1 MVC中有一个应用程序。

我有两个表CallsAspNetUsersAspNetUsers有很多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获得呼叫的更好方法是什么? 谢谢!

asp.net-core-mvc entity-framework-core asp.net-core-identity
1个回答
0
投票

您可以像设置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();
}
© www.soinside.com 2019 - 2024. All rights reserved.