【问题标题】:EF Core how add Primary KeyEF Core 如何添加主键
【发布时间】:2020-01-05 05:21:05
【问题描述】:

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

现在我的问题是当我尝试运行 Add-Migration 时,会抛出

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

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

编辑 1: 模型生成器

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


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

【问题讨论】:

    标签: c# entity-framework


    【解决方案1】:

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

    我是一个细菌怪胎,所以我的代码写得很干净。这就是为什么例如当我像下面这样创建Model 时,我为每个Id 创建一个EntityBase

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

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

    【讨论】:

    • 必须在哪里添加此代码?我正在尝试使用模型生成器,但找不到名为 OnModelCreating. 的方法来覆盖它
    • @JuanPabloGomez 你在使用 EF Code-First 吗?
    • 我要发布我的模型生成器。
    • EF Core 文档中,我必须使用 Add-Migration 构建我的数据库,我真的不知道这是否是代码优先方法。但我的模型是基于我编写的类。
    • 只有一个小问题你知道为什么注释不起作用吗?
    【解决方案2】:

    如果你使用 EF 核心添加

     .UseSerialColumn();
    

    例子

    modelBuilder.Entity<JobItem>(entity =>
            {
                entity.ToTable("jobs");
    
                entity.Property(e => e.Id)
                    .HasColumnName("id")
                    .UseSerialColumn();
    });
    

    我正在使用 EF.postgres

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      • 1970-01-01
      • 2019-02-17
      • 1970-01-01
      相关资源
      最近更新 更多