EF Core如何添加主键

时间:2016-12-27 16:55:28

标签: c# entity-framework

我把这个类定义放到了SQLite的Ef Core Model中。

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

现在我的问题是当我尝试运行添加迁移时,抛出

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

如何将主键添加到sqlite的EF Core Model?

编辑1:模型生成器

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


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

2 个答案:

答案 0 :(得分:4)

为什么不使用fluent api

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

试试这个,我认为你的问题现在已经解决了。

<强> --- ---更新

首先创建DbContext

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

在您的应用根目录中创建迁移文件夹并在那里进行Configuration课程:

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" }
        //    );
        //
    }
}

我是一个Germ Freak,所以我写的代码非常干净。这就是为什么当我在下面制作一个Model时,我为每个EntityBase创建一个Id

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

并将其实施到我的Model

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

对于映射我创建另一个类,如下所示,并使用Fluent Api

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

    }
}

但是如果你不想经历所有麻烦,你可以轻松地在你的DbContext's OnModelCreating方法中插入流畅的api就像我在开始时所说的那样。顺便提一下,如果您使用的是流畅的api,则不应使用数据注释。快乐的编码。

答案 1 :(得分:0)

如果您使用EF核心添加

 .UseSerialColumn();

示例

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

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

我正在使用EF.postgres