在2.1中使用EF Core进行数据库查询

时间:2018-10-11 18:24:13

标签: c# database asp.net-core entity-framework-core

我刚刚创建了一个带有身份的全新核心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;
    }

2 个答案:

答案 0 :(得分:0)

using (var context = new ApplicationDbContext())
{
    var user = await context.UserAddresses.SingleAsync(x => x.Id == UserId);

    return user;
}

添加一个空的构造函数:

public ApplicationDbContext() {}

答案 1 :(得分:0)

app.module.ts

您还可以获得单个地址,第一个地址或最后一个地址等。

  

Startup.cs中的配置

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();