EF Core如何添加主键

8
我已经在Ef Core模型中定义了这个类,用于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); }
    }
}

现在我的问题是,当我尝试运行Add-Migration时,会抛出错误。
System.InvalidOperationException: The entity type 'Ejercicios' requires a primary key to be defined.

如何在 EF Core 模型中为 SQLite 添加主键? 编辑1:模型生成器
public class MyContext : DbContext
{
    public DbSet<Ejercicios> Ejercicios { get; set; }


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

对于 EF 7,请查看 https://dev59.com/N2Ij5IYBdhLWcg3w4Y2S#75425849。 - Vivek Nuna
2个回答

10

你为什么不使用流畅的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" }
        //    );
        //
    }
}

我是一个洁癖患者,所以编写代码时非常注重整洁。比如,当我制作下面这样的Model时,我会为每个Id创建一个EntityBase

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

并将其实现到我的模型中:

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

    }
}

但如果您不想费太多力气,您可以轻松地将流利API插入到您的DbContext's OnModelCreating方法中,就像我在开头所说的那样。顺便提醒一下,如果您正在使用流利API,则不应使用数据注释。祝编码愉快。


这段代码应该添加在哪里?我尝试在模型生成器中,但找不到一个名为 OnModelCreating 的方法来覆盖它。 - Juan Pablo Gomez
@JuanPabloGomez 你正在使用EF Code-First吗? - Masoud Andalibi
@JuanPabloGomez 随时可以,很乐意帮忙。 - Masoud Andalibi
1
只有一个小问题,你知道为什么注解不起作用吗? - Juan Pablo Gomez
让我们在聊天中继续这个讨论 - Masoud Andalibi
显示剩余2条评论

2
如果您使用EF Core添加
 .UseSerialColumn();

例子

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

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

我使用EF.postgres。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接