【发布时间】:2019-03-16 22:14:51
【问题描述】:
我刚刚创建了一个带有身份的全新核心 MVC 应用程序。我这辈子都不知道如何让实体框架进行数据库查询。
我有一个 ApplicationDBContext
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
每当我尝试使用它时,它只会告诉我我没有发送任何选项。
我正在尝试对我的 UserAddresses 表运行查询,并将我的 ASPNetUsers 表更改为 Users。
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
// Update the ApplicationUser Table to Users and change primary column to UserId
builder.Entity<ApplicationUser>(entity =>
{
entity.ToTable("Users");
entity.Property(e => e.Id).HasColumnName("UserId");
});
}
public DbSet<UserAddress> UserAddresses { get; set; }
这是整个班级
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// Customize the ASP.NET Identity model and override the defaults if needed.
// For example, you can rename the ASP.NET Identity table names and more.
// Add your customizations after calling base.OnModelCreating(builder);
// Update the ApplicationUser Table to Users and change primary column to UserId
builder.Entity<ApplicationUser>(entity =>
{
entity.ToTable("Users");
entity.Property(e => e.Id).HasColumnName("UserId");
});
}
public DbSet<UserAddress> UserAddresses { get; set; }
}
如何连接到 DBContext 以使用 EF 运行查询
更新
我可以通过像这样的构造函数将我的_context 传递给控制器来获取它
private ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
【问题讨论】:
-
如果将工具从
IdentityDbContext<ApplicationUser>更改为DbContext会发生什么? -
您想运行什么查询?分享我们相关的代码,你从哪里得到这个错误。只看到配置,没找到你怎么调用
_context。
标签: c# database asp.net-core entity-framework-core