Asp.Net Core: Add data to IdentityDbContext or use DbContext

asp.net asp.net-core asp.net-identity entity-framework-6 entity-framework-core

Accepted Answer

Can I add my tables to IdentityDbContext, like this:

Yes, that is how custom tables are made. There's no need to make anotherDbContext . E.g.

public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }

    public DbSet<Project> Projects { get; set; }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        builder.Entity<Project>(entity =>
        {
            entity.Property(e => e.Name)
                .IsRequired()
                .HasMaxLength(50);
        });

        base.OnModelCreating(builder);
    }
}

You may need to leave right now.dotnet ef migrations add Initial and dotnet ef database update for moving databases.

using (var db = new ApplicationDbContext()) {...}

Zzz-31-Zzz, youApplicationDbContext inside controller. They become closely connected if you do this, making it impossible to use unit tests.

Instead, you delegate management of it to a dependency inversion (DI) container. E.g.

public class UserController : Controller
{
    private readonly ApplicationDbContext _context;

    public UserController(ApplicationDbContext context)
    {
        _context = context;
    }

    [AllowAnonymous]
    [HttpGet]
    public IEnumerable<Project> GetRoles()
    {
        return _context.Projects;
    }
}
8
5/16/2018 7:57:48 PM

Popular Answer

ZZZ_tmp


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow