我在 .net Core 项目中使用 EF Core 和 Identity 库,因此我必须为我的实体(产品等)和 Identity 创建单独的上下文,但我无法为单独的上下文创建关系。当我收集所有单个上下文(IdentityDb Context)中的数据,我可以创建关系并访问它。
namespace Auction_DataAccess.Context
{
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Bid> Bids { get; set; }
public DbSet<PaymentHistory> PaymentHistories { get; set; }
public DbSet<Vehicle> Vehicles { get; set; }
public DbSet<ApplicationUser> ApplicationUsers { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Bid>().HasKey(b => b.Id);
builder.Entity<PaymentHistory>().HasKey(b => b.Id);
builder.Entity<Vehicle>().HasKey(b => b.Id);
builder.Entity<ApplicationUser>(e => e.ToTable(name: "Users"));
builder.Entity<IdentityUserLogin<string>>().HasKey(e => new { e.LoginProvider, e.ProviderKey });
builder.Entity<IdentityUserRole<string>>().HasKey(e => new { e.UserId, e.RoleId });
builder.Entity<IdentityUserToken<string>>().HasKey(e => new { e.UserId, e.LoginProvider, e.Name });
}
}
}
在 IdentityDb 上下文中将身份(用户等)和其他数据(产品等)保存在一起是否安全?
保留身份(用户等)和其他数据(产品等)是否安全 一起在 IdentityDb 上下文中?
是的,将您的身份数据和其他业务相关数据保存在同一个 IdentityDbContext 中通常是安全的。
据我所知,有一些好处,例如:
您可以在同一上下文中轻松定义业务实体和身份数据之间的关系,这可以简化您的数据库结构和代码库。
只需管理一个DbContext,降低了复杂性。所有迁移、数据库交互和事务管理都通过单个上下文进行处理。
对于单独的DbContext,大多数时候我不建议使用它。但是,如果有一天您可能决定选择第三方身份验证提供商,而忘记自己管理身份。在这一点上,我认为这是有好处的,您可以进行一些迁移,扔掉不再需要的身份数据库。