EF Core如何添加主键 [英] EF Core how add Primary Key

查看:920
本文介绍了EF Core如何添加主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SQLite的Ef核心模型中有了这个类定义。

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.

如何为sqlite的EF核心模型添加主键?

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

编辑1:模型生成器

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


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


推荐答案

为什么您不使用流利的api 吗?

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

尝试一下,我认为您的问题现在已经解决。

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

---更新---

创建您的 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());
    }
}

在应用程序根目录中创建一个迁移文件夹,然后使<那里的code> Configuration 类:

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

我是胚芽怪胎,所以我写的代码很干净。这就是为什么例如当我制作如下的 Model 时,我为每个创建一个 EntityBase ID

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

并将其实现为我的 Model

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

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

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

    }
}

但是,如果您不想遇到所有麻烦,则可以轻松地将流畅的api插入 DbContext的OnModelCreating 方法中。顺便提一下,如果您使用的是流畅的api,则不应该使用数据注释。快乐编码。

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.

这篇关于EF Core如何添加主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆