Juan Pablo Gomez
Juan Pablo Gomez

Reputation: 5524

EF Core how add Primary Key

I have this class definition into Ef Core Model for SQLite.

public class Ejercicios : BaseModel
{
    private int _TipoEjercicio;
    [Key]
    public int TipoEjercicio
    {
        get { return _TipoEjercicio; }
        set { SetProperty(ref _TipoEjercicio, value); }
    }

    private string _DescripcionEjercicio;
    public string DescripcionEjercicio
    {
        get { return _DescripcionEjercicio; }
        set { SetProperty(ref _DescripcionEjercicio, value); }
    }

    private string _HexForeColor;
    public string HexForeColor
    {
        get { return _HexForeColor; }
        set { SetProperty(ref _HexForeColor, value); }
    }

    private string _HexBackGroundColor;
    public string HexBackGroundColor
    {
        get { return _HexBackGroundColor; }
        set { SetProperty(ref _HexBackGroundColor, value); }
    }
}

Now my problem is when I try to run Add-Migration, throws

System.InvalidOperationException: The entity type 'Ejercicios' requires a primary key to be defined.

How to add primary key to an EF Core Model for sqlite ?

Edit 1: Model Generator

public class MyContext : DbContext
{
    public DbSet<Ejercicios> Ejercicios { get; set; }


    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Filename=MyDb.db");
    }
}

Upvotes: 8

Views: 42266

Answers (2)

mdimai666
mdimai666

Reputation: 787

If you use EF core add

 .UseSerialColumn();

Example

modelBuilder.Entity<JobItem>(entity =>
        {
            entity.ToTable("jobs");

            entity.Property(e => e.Id)
                .HasColumnName("id")
                .UseSerialColumn();
});

Im using EF.postgres

Upvotes: 2

Masoud Andalibi
Masoud Andalibi

Reputation: 3228

Why don't you use fluent api ?

modelBuilder.Entity<Ejercicios>()
    .HasKey(p => new p.TipoEjercicio);

Try this out, i think your problem is now solved.

---Update---

Create Your DbContext First:

public class MyDbContext : DbContext
{
    public MyDbContext()
        : base("name=MyConnection")
    {
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyDbContext, YourApplication.Migrations.Configuration>("MyConnection")); 
    }
    public DbSet<Users> Users { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        //here you can MAP Your Models/Entities, but i am going to show you something more interesting. so keep up. 
        modelBuilder.Configurations.Add(new UsersMap());
    }
}

Create a Migration Folder in your app root And make Configuration class there:

internal sealed class Configuration : DbMigrationsConfiguration<YourApplication.Infrastructure.Data.MyDbContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;

        AutomaticMigrationDataLossAllowed = true;
        ContextKey = "YourApplication.Infrastructure.Data.MyDbContext";
    }

    protected override void Seed(YourApplication.Infrastructure.Data.MyDbContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

I am a Germ Freak, so i write my codes very clean. That's why when for example i made a Model like below, i create an EntityBase for every Id:

public class EntityBase
{
    public int Id { get; set; }
}

And Implement it to my Model :

public class User: EntityBase
{
    public string Example1{ get; set; }
    public string Example2{ get; set; }
    public string Example3{ get; set; }
}

And For Mapping I Create another Class like below and use Fluent Api:

public class UserMap : EntityTypeConfiguration<User>
{
    public UserMap()
    {
        ToTable("TblUser");
        HasKey(x => x.Id);
        Property(x => x.Example1)
            .IsRequired();
        //etc

    }
}

But if you don't want to go through all the trouble you can easily just insert the fluent api in your DbContext's OnModelCreating Method Like i said at start. By the way be aware if you are using fluent api, you Shouldn't use Data Annotations. Happy Coding.

Upvotes: 10

Related Questions