[英]Database Query with EF Core in 2.1
我刚刚创建了一个带有身份的全新核心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;
}
using (var context = new ApplicationDbContext())
{
var user = await context.UserAddresses.SingleAsync(x => x.Id == UserId);
return user;
}
添加一个空的构造函数:
public ApplicationDbContext() {}
private ApplicationDbContext _context;
public HomeController(ApplicationDbContext context)
{
_context = context;
}
// this will get the userId of currently loggedIn user
userId = User.Identity.GetUserId()
// this line get all the address of loggedIn user from UserAddresses table
_context.UserAddresses.Where(a => a.UserId == userId).ToList();
您还可以获取单个地址,第一个地址或最后一个地址等。
在Startup.cs中进行配置
services.AddIdentity<ApplicationUser>()
.AddEntityFrameworkStores<AppIdentityDbContext>()
.AddDefaultTokenProviders();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.