Reputation: 436
I created model with some fields (including public int Id {get; set; }
). I try to add the first migration: Add-Migration MyModel
, after which a file with empty Up() and Down() methods is created.
Is it possible that the problem is that the db context file is empty?
ApplicationDbContext.cs
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace TimeTracker.Data
{
public class ApplicationDbContext : IdentityDbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
}
I already tried solutions from other questions.
I tried Add-Migration InitialCreate
, then Update-Database
, remove all migrations and database, create new project. It didn't solve the problem.
Upvotes: 1
Views: 446
Reputation: 1973
You need to add the newly created Model in the ApplicationDbContext Class.
public DbSet<ModelName> ModelPropertyName { get; set; }
Upvotes: 1
Reputation: 2231
Your DB context does not know that you want your entity to be mapped to database. You must add some DbSet property before.
public DbSet<MyEntity> MyEntities { get; set; }
If Your entity would have some relationship with foreign key there is no need to add both class properties. EF Core will see this relationship if you specify navigation property in your entity class or/and customize it in OnModelCreating
method with Fluent API
You can also cusomize your migration with attributes or using Fluent API your EFContext's method OnModelCreating(ModelBuilder modelBuilder):
public class Blog
{
public int BlogId { get; set; }
[Required]
public string Url { get; set; }
}
or
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.IsRequired();
}
}
Upvotes: 1