EF Core 3.1 - System.InvalidOperationException: 'The entity type 'Pntbec03' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.'

leo del ciello 66 Reputation points
2024-05-29T13:46:26.23+00:00

Hello .

I need to handle a EF Core Entity relating to a table , but without having EF managing all its columns , but just a subset of them.

I have scaffolded the small database to which the table belongs into a DbContext , and I though I could create another DbContext inheriting from this one , and substituting the mofrl of the table with another one, containing only the properties / columns I really need. The original table / entity is called Pntbec03, so I created a new model resembling Pntbec03 but only with a subset of Pntbec03 , which I called Pntbec03d (final 'd' for 'derived'). in the new DbContext's OnModelCreating I removed the old Modelbuilder.Entity<Pntbec03> (..) call and i substituted it with a Modelbuilder.Entity <Pntbec03d>(...) call , which only creates the entity.Property (...) corresponding to the fields in Pntbec03d. Everything seems to be fine up until I try to launch a simple query on the Pntbeco3d DbSet, then I get this exception :

System.InvalidOperationException: 'The entity type 'Pntbec03' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.'

Which is kind of weird since I am calling a query on Pntbec0d3, and not Pntbec03

The relevant code is the following .

Original scaffolded DbContext :

public partial class A01DB2Context : DbContext

{

public A01DB2Context()

{

}

public A01DB2Context(DbContextOptions<A01DB2Context> options)

: base(options)

{

}

public virtual DbSet<Astbap> Astbap { get; set; }

public virtual DbSet<Pntbap03> Pntbap03 { get; set; }

public virtual DbSet<Pntbcr04> Pntbcr04 { get; set; }

public virtual DbSet<Pntbcrbs> Pntbcrbs { get; set; }

public virtual DbSet<Pntbec03> Pntbec03 { get; set; }

public virtual DbSet<Pntbrb03> Pntbrb03 { get; set; }

public virtual DbSet<Pntbri02> Pntbri02 { get; set; }

public virtual DbSet<Pntbrrbt> Pntbrrbt { get; set; }

public virtual DbSet<Pntbrres> Pntbrres { get; set; }

public virtual DbSet<Pnvorn00> Pnvorn00 { get; set; }

public virtual DbSet<Pnvosp01> Pnvosp01 { get; set; }

public virtual DbSet<T13e> T13e { get; set; }

public virtual DbSet<T84e> T84e { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{

if (!optionsBuilder.IsConfigured)

{

#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.

optionsBuilder.UseDb2("UID=**;PWD=**;DataBase=**;Server=**;", x => x.SetServerInfo(IBMDBServerType.OS390));

}

}

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity<Astbap>(entity =>

{

entity.HasNoKey();

entity.ToTable("ASTBAP", "AN1T503");

entity.Property(e => e.ApAbiUpe)

.IsRequired()

.HasColumnName("AP_ABI_UPE")

.HasColumnType("char(5)");

................................................

});

modelBuilder.Entity<Pntbap03>(entity =>

{

entity.HasNoKey();

entity.ToTable("PNTBAP03", "TEFT0");

entity.Property(e => e.Ap03AnnoValidita)

.IsRequired()

.HasColumnName("AP03_ANNO_VALIDITA")

.HasColumnType("char(4)");

.................................................

});

modelBuilder.Entity<Pntbcr04>(entity =>

{

entity.HasNoKey();

entity.ToTable("PNTBCR04", "TEFT0");

entity.Property(e => e.Cr04AnnoRiferim)

.IsRequired()

.HasColumnName("CR04_ANNO_RIFERIM")

.HasColumnType("char(4)");

.................................................

});

modelBuilder.Entity<Pntbcrbs>(entity =>

{

entity.HasNoKey();

entity.ToTable("PNTBCRBS", "TEFT0");

entity.Property(e => e.CrbsAnnoRiferim)

.IsRequired()

.HasColumnName("CRBS_ANNO_RIFERIM")

.HasColumnType("char(4)");

.................................................

});

modelBuilder.Entity<Pntbec03>(entity =>

{

entity.HasNoKey();

entity.ToTable("PNTBEC03", "TEFT0");

entity.Property(e => e.Ec03AnnoEmiss)

.HasColumnName("EC03_ANNO_EMISS")

.HasColumnType("smallint(2)");

entity.Property(e => e.Ec03AnnoValidita)

.IsRequired()

.HasColumnName("EC03_ANNO_VALIDITA")

.HasColumnType("char(4)");

entity.Property(e => e.Ec03Catg)

.IsRequired()

.HasColumnName("EC03_CATG")

.HasColumnType("char(3)");

entity.Property(e => e.Ec03Cert)

.IsRequired()

.HasColumnName("EC03_CERT")

.HasColumnType("char(8)");

entity.Property(e => e.Ec03CodCabEmiss)

.IsRequired()

.HasColumnName("EC03_COD_CAB_EMISS")

.HasColumnType("char(7)");

entity.Property(e => e.Ec03CodGest1)

.IsRequired()

.HasColumnName("EC03_COD_GEST_1")

.HasColumnType("char(1)");

entity.Property(e => e.Ec03CodGest2)

.IsRequired()

.HasColumnName("EC03_COD_GEST_2")

.HasColumnType("char(1)");

entity.Property(e => e.Ec03DtaAl)

.IsRequired()

.HasColumnName("EC03_DTA_AL")

.HasColumnType("char(6)");

entity.Property(e => e.Ec03DtaDal)

.IsRequired()

.HasColumnName("EC03_DTA_DAL")

.HasColumnType("char(6)");

entity.Property(e => e.Ec03DtaPreFile)

.HasColumnName("EC03_DTA_PRE_FILE")

.HasColumnType("date(4)");

entity.Property(e => e.Ec03IdentFlusso)

.IsRequired()

.HasColumnName("EC03_IDENT_FLUSSO")

.HasColumnType("char(3)");

entity.Property(e => e.Ec03ImpInPag)

.HasColumnName("EC03_IMP_IN_PAG")

.HasColumnType("decimal(13, 4)");

entity.Property(e => e.Ec03ImpLordo)

.HasColumnName("EC03_IMP_LORDO")

.HasColumnType("decimal(13, 4)");

entity.Property(e => e.Ec03MeseEmiss)

.HasColumnName("EC03_MESE_EMISS")

.HasColumnType("smallint(2)");

entity.Property(e => e.Ec03NatMovim)

.IsRequired()

.HasColumnName("EC03_NAT_MOVIM")

.HasColumnType("char(2)");

entity.Property(e => e.Ec03OraPreFile)

.HasColumnName("EC03_ORA_PRE_FILE")

.HasColumnType("time(0)");

entity.Property(e => e.Ec03RataProgP1r)

.HasColumnName("EC03_RATA_PROG_P1R")

.HasColumnType("smallint(2)");

entity.Property(e => e.Ec03Sed1)

.IsRequired()

.HasColumnName("EC03_SED1")

.HasColumnType("char(2)");

entity.Property(e => e.Ec03Sed1Pag)

.HasColumnName("EC03_SED1_PAG")

.HasColumnType("char(2)");

entity.Property(e => e.Ec03Sed2)

.IsRequired()

.HasColumnName("EC03_SED2")

.HasColumnType("char(2)");

entity.Property(e => e.Ec03Sed2Pag)

.HasColumnName("EC03_SED2_PAG")

.HasColumnType("char(2)");

entity.Property(e => e.Ec03UffPagEmiss)

.IsRequired()

.HasColumnName("EC03_UFF_PAG_EMISS")

.HasColumnType("char(3)");

});

...........................................

OnModelCreatingPartial(modelBuilder);

}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

}

The derived DbContext is :

public partial class DerivedDbContext:A01DB2Context

{

public DerivedDbContext()

{

}

public DerivedDbContext(DbContextOptions<A01DB2Context> options)

: base(options)

{

}

//public virtual DbSet<Astbap> Astbap { get; set; }

//public virtual DbSet<Pntbap03> Pntbap03 { get; set; }

//public virtual DbSet<Pntbcr04> Pntbcr04 { get; set; }

//public virtual DbSet<Pntbcrbs> Pntbcrbs { get; set; }

//public virtual DbSet<Pntbec03> Pntbec03 { get; set; }

public virtual DbSet<Pntbec03d> Pntbec03d { get; set; }

//public virtual DbSet<Pntbrb03> Pntbrb03 { get; set; }

//public virtual DbSet<Pntbri02> Pntbri02 { get; set; }

//public virtual DbSet<Pntbrrbt> Pntbrrbt { get; set; }

//public virtual DbSet<Pntbrres> Pntbrres { get; set; }

//public virtual DbSet<Pnvorn00> Pnvorn00 { get; set; }

//public virtual DbSet<Pnvosp01> Pnvosp01 { get; set; }

//public virtual DbSet<T13e> T13e { get; set; }

//public virtual DbSet<T84e> T84e { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

{

if (!optionsBuilder.IsConfigured)

{

#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.

optionsBuilder.UseDb2("UID=**;PWD=**;DataBase=**;Server=**;", x => x.SetServerInfo(IBMDBServerType.OS390));

}

}

protected override void OnModelCreating(ModelBuilder modelBuilder)

{

modelBuilder.Entity<Astbap>(entity =>

{

entity.HasNoKey();

entity.ToTable("ASTBAP", "AN1T503");

entity.Property(e => e.ApAbiUpe)

.IsRequired()

.HasColumnName("AP_ABI_UPE")

.HasColumnType("char(5)");

................................................

});

modelBuilder.Entity<Pntbap03>(entity =>

{

entity.HasNoKey();

entity.ToTable("PNTBAP03", "TEFT0");

entity.Property(e => e.Ap03AnnoValidita)

.IsRequired()

.HasColumnName("AP03_ANNO_VALIDITA")

.HasColumnType("char(4)");

.................................................

});

modelBuilder.Entity<Pntbcr04>(entity =>

{

entity.HasNoKey();

entity.ToTable("PNTBCR04", "TEFT0");

entity.Property(e => e.Cr04AnnoRiferim)

.IsRequired()

.HasColumnName("CR04_ANNO_RIFERIM")

.HasColumnType("char(4)");

.................................................

});

modelBuilder.Entity<Pntbcrbs>(entity =>

{

entity.HasNoKey();

entity.ToTable("PNTBCRBS", "TEFT0");

entity.Property(e => e.CrbsAnnoRiferim)

.IsRequired()

.HasColumnName("CRBS_ANNO_RIFERIM")

.HasColumnType("char(4)");

.................................................

});

modelBuilder.Entity<Pntbec03d>(entity =>

{

entity.HasNoKey();

entity.ToTable("PNTBEC03", "TEFT0");

entity.Property(e => e.Ec03AnnoEmiss)

.HasColumnName("EC03_ANNO_EMISS")

.HasColumnType("smallint(2)");

entity.Property(e => e.Ec03AnnoValidita)

.IsRequired()

.HasColumnName("EC03_ANNO_VALIDITA")

.HasColumnType("char(4)");

entity.Property(e => e.Ec03Catg)

.IsRequired()

.HasColumnName("EC03_CATG")

.HasColumnType("char(3)");

entity.Property(e => e.Ec03Cert)

.IsRequired()

.HasColumnName("EC03_CERT")

.HasColumnType("char(8)");

entity.Property(e => e.Ec03CodCabEmiss)

.IsRequired()

.HasColumnName("EC03_COD_CAB_EMISS")

.HasColumnType("char(7)");

entity.Property(e => e.Ec03CodGest1)

.IsRequired()

.HasColumnName("EC03_COD_GEST_1")

.HasColumnType("char(1)");

entity.Property(e => e.Ec03CodGest2)

.IsRequired()

.HasColumnName("EC03_COD_GEST_2")

.HasColumnType("char(1)");

entity.Property(e => e.Ec03DtaAl)

.IsRequired()

.HasColumnName("EC03_DTA_AL")

.HasColumnType("char(6)");

entity.Property(e => e.Ec03DtaDal)

.IsRequired()

.HasColumnName("EC03_DTA_DAL")

.HasColumnType("char(6)");

/*

entity.Property(e => e.Ec03DtaPreFile)

.HasColumnName("EC03_DTA_PRE_FILE")

.HasColumnType("date(4)");

*/

entity.Property(e => e.Ec03IdentFlusso)

.IsRequired()

.HasColumnName("EC03_IDENT_FLUSSO")

.HasColumnType("char(3)");

/*

entity.Property(e => e.Ec03ImpInPag)

.HasColumnName("EC03_IMP_IN_PAG")

.HasColumnType("decimal(13, 4)");

entity.Property(e => e.Ec03ImpLordo)

.HasColumnName("EC03_IMP_LORDO")

.HasColumnType("decimal(13, 4)");

entity.Property(e => e.Ec03MeseEmiss)

.HasColumnName("EC03_MESE_EMISS")

.HasColumnType("smallint(2)");

*/

entity.Property(e => e.Ec03NatMovim)

.IsRequired()

.HasColumnName("EC03_NAT_MOVIM")

.HasColumnType("char(2)");

/*

entity.Property(e => e.Ec03OraPreFile)

.HasColumnName("EC03_ORA_PRE_FILE")

.HasColumnType("time(0)");

*/

entity.Property(e => e.Ec03RataProgP1r)

.HasColumnName("EC03_RATA_PROG_P1R")

.HasColumnType("smallint(2)");

entity.Property(e => e.Ec03Sed1)

.IsRequired()

.HasColumnName("EC03_SED1")

.HasColumnType("char(2)");

/*

entity.Property(e => e.Ec03Sed1Pag)

.HasColumnName("EC03_SED1_PAG")

.HasColumnType("char(2)");

*/

entity.Property(e => e.Ec03Sed2)

.IsRequired()

.HasColumnName("EC03_SED2")

.HasColumnType("char(2)");

/*

entity.Property(e => e.Ec03Sed2Pag)

.HasColumnName("EC03_SED2_PAG")

.HasColumnType("char(2)");

*/

entity.Property(e => e.Ec03UffPagEmiss)

.IsRequired()

.HasColumnName("EC03_UFF_PAG_EMISS")

.HasColumnType("char(3)");

});

//modelBuilder.Entity<Pntbec03>(entity =>

//{

// entity.HasNoKey();

// entity.ToTable("PNTBEC03", "TEFT0");

// entity.Property(e => e.Ec03AnnoEmiss)

// .HasColumnName("EC03_ANNO_EMISS")

// .HasColumnType("smallint(2)");

// entity.Property(e => e.Ec03AnnoValidita)

// .IsRequired()

// .HasColumnName("EC03_ANNO_VALIDITA")

// .HasColumnType("char(4)");

// entity.Property(e => e.Ec03Catg)

// .IsRequired()

// .HasColumnName("EC03_CATG")

// .HasColumnType("char(3)");

// entity.Property(e => e.Ec03Cert)

// .IsRequired()

// .HasColumnName("EC03_CERT")

// .HasColumnType("char(8)");

// entity.Property(e => e.Ec03CodCabEmiss)

// .IsRequired()

// .HasColumnName("EC03_COD_CAB_EMISS")

// .HasColumnType("char(7)");

// entity.Property(e => e.Ec03CodGest1)

// .IsRequired()

// .HasColumnName("EC03_COD_GEST_1")

// .HasColumnType("char(1)");

// entity.Property(e => e.Ec03CodGest2)

// .IsRequired()

// .HasColumnName("EC03_COD_GEST_2")

// .HasColumnType("char(1)");

// entity.Property(e => e.Ec03DtaAl)

// .IsRequired()

// .HasColumnName("EC03_DTA_AL")

// .HasColumnType("char(6)");

// entity.Property(e => e.Ec03DtaDal)

// .IsRequired()

// .HasColumnName("EC03_DTA_DAL")

// .HasColumnType("char(6)");

// entity.Property(e => e.Ec03DtaPreFile)

// .HasColumnName("EC03_DTA_PRE_FILE")

// .HasColumnType("date(4)");

// entity.Property(e => e.Ec03IdentFlusso)

// .IsRequired()

// .HasColumnName("EC03_IDENT_FLUSSO")

// .HasColumnType("char(3)");

// entity.Property(e => e.Ec03ImpInPag)

// .HasColumnName("EC03_IMP_IN_PAG")

// .HasColumnType("decimal(13, 4)");

// entity.Property(e => e.Ec03ImpLordo)

// .HasColumnName("EC03_IMP_LORDO")

// .HasColumnType("decimal(13, 4)");

// entity.Property(e => e.Ec03MeseEmiss)

// .HasColumnName("EC03_MESE_EMISS")

// .HasColumnType("smallint(2)");

// entity.Property(e => e.Ec03NatMovim)

// .IsRequired()

// .HasColumnName("EC03_NAT_MOVIM")

// .HasColumnType("char(2)");

// entity.Property(e => e.Ec03OraPreFile)

// .HasColumnName("EC03_ORA_PRE_FILE")

// .HasColumnType("time(0)");

// entity.Property(e => e.Ec03RataProgP1r)

// .HasColumnName("EC03_RATA_PROG_P1R")

// .HasColumnType("smallint(2)");

// entity.Property(e => e.Ec03Sed1)

// .IsRequired()

// .HasColumnName("EC03_SED1")

// .HasColumnType("char(2)");

// entity.Property(e => e.Ec03Sed1Pag)

// .HasColumnName("EC03_SED1_PAG")

// .HasColumnType("char(2)");

// entity.Property(e => e.Ec03Sed2)

// .IsRequired()

// .HasColumnName("EC03_SED2")

// .HasColumnType("char(2)");

// entity.Property(e => e.Ec03Sed2Pag)

// .HasColumnName("EC03_SED2_PAG")

// .HasColumnType("char(2)");

// entity.Property(e => e.Ec03UffPagEmiss)

// .IsRequired()

// .HasColumnName("EC03_UFF_PAG_EMISS")

// .HasColumnType("char(3)");

//});

...........................................

OnModelCreatingPartial(modelBuilder);

}

partial void OnModelCreatingPartial(ModelBuilder modelBuilder);

}

The query causing the Exception is the following :

DerivedDbContext DbCtxt = new DerivedDbContext();

var ec03 = DbCtxt.Pntbec03d;

var l =ec03.Where(x =>

x.Ec03Sed1 == CP.Sed1 &&

x.Ec03Sed2 == CP.Sed2 &&

x.Ec03Catg == CP.Categoria &&

x.Ec03Cert == CP.Certificato &&

x.Ec03CodGest1 + x.Ec03CodGest2 == CP.ProgressivoSoggetto &&

x.Ec03AnnoValidita == CP.Anno

).ToList();

What could be the problem ?

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
751 questions
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,921 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 28,536 Reputation points
    2024-05-29T18:11:57.02+00:00

    The derived class constructor does not invoke the base constructor.

    public DerivedDbContext() : base()
    {
    }
    
    
    

    The code is very hard to read. Use the "code block" option when posting code on the forum. Also, don't post commented code.

    I believe there are other issues with your approach. The implementation does not pass the DbContext options.

    What's the purpose of the derived class? Seems like like unnecessary complexity.


  2. Hongrui Yu-MSFT 2,465 Reputation points Microsoft Vendor
    2024-05-30T07:27:11.6966667+00:00

    Hi,@leo del ciello. Welcome to Microsoft Q&A. 

    Solution: Set keys for dbcontext and entity classes in your application

    a.Delete entity.HasNoKey() under DbContext (at least delete HasNoKey of parent DbContext)

    Example:

    
            modelBuilder.Entity<User>(entity =>
    
            {
    
                entity
    
                    .HasNoKey()        //Delete
    
                    .ToTable("users");
    
     
    
                entity.Property(e => e.Age).HasColumnName("age");
    
                entity.Property(e => e.Email).HasColumnName("email");
    
                entity.Property(e => e.Name).HasColumnName("name");
    
            });
    
    

    b.Add [Key] to an attribute on the corresponding entity class(At least add [Key] to the parent entity class)

    Example:

    
    public partial class User
    
    {
    
        [Key]        //Add
    
        public string Name { get; set; } = null!;
    
     
    
        public int Age { get; set; }
    
     
    
        public string Email { get; set; } = null!;
    
    }
    
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.