Asp.NET Core 3.1 MVCにEF CoreとIdentityを備えたアプリケーションがあります。
Calls
とAspNetUsers
2つのテーブルCalls
ありAspNetUsers
。 AspNetUsers
は多くのCalls
あり、1つのCall
は1つのAspNetUsers
ます。
Calls
テーブルの構造は問題ないと思います。しかし今、私はAspNetUsers
からのCalls
を取得する必要があります。
CallsController
私は試みていIList<Call> calls = this.User.Calls;
: IList<Call> calls = this.User.Calls;
しかし成功しません。
私は試した:
IList<Call> calls = this._context.Calls.Where(x => x.UserId == this._userManager.GetUserId(this.User)).ToList();
私は成功しました。しかし、それは正しいのでしょうか?
したがって、 ApplicationUser
は、次のようなIDクラスとApplicationUser
があります。
public class ApplicationUser : IdentityUser
{
public virtual IList<Call> Calls { get; set; }
}
そして、 ConfigureServices
メソッドのStartup
クラスで:
services.AddDefaultIdentity<ApplicationUser>(options =>
options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
それでは、AspNetUsersから呼び出しを取得するためのより良い方法は何ですか? ありがとう!
次のようにApplicationUser
を設定でき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();
}
ApplicationUserは
public class ApplicationUser : IdentityUser
{
public virtual ICollection<Call> Calls { get; set; }
}
呼び出しエンティティは
public class Call
{
public int ID { get; set; }
//...
public string ApplicationUserId { get; set; }
[ForeignKey(nameof(ApplicationUserId))]
public virtual ApplicationUser ApplicationUser { get; set; }
}
そしてもちろん、このようにDbContextのOnModeCreatingメソッドをオーバーライドする必要があります。
public class ApplicationDbContext: DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options){}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Call>()
.HasOne(x => x.ApplicationUser)
.WithMany(x => x.Calls);
}
//...DbSets..
}
最後に、すべての通話をApplicationUserのCallsコレクションに読み込みます。
var user = await _context.ApplicationUsers.FindAsync(_userManager.GetUserId(this.User));
await context.Entry(user)
.Collection(x => x.Calls)
.LoadAsync();
これで、すべての通話が現在のユーザーのCallsコレクションに読み込まれました。