Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");
    }
}
like image 720
Juan Pablo Gomez Avatar asked Dec 27 '16 16:12

Juan Pablo Gomez


1 Answers

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.

like image 98
Masoud Andalibi Avatar answered Sep 18 '22 21:09

Masoud Andalibi