Is there a way to take First() from a hierarchy table in Entity Framework Core?

.net-core entity-framework-core sql-server


Is there any way to access a table that is a hierarchy?

Entity Framework Core returns null from the First() method, the table is NOT empty. I use SQL Server to store the table.

public class TestProjectEFDbContext : DbContext
    private const string connectionString = @"data source=DESKTOP-I2JBLKP; Initial Catalog=TestProjectEF;  Trusted_Connection=True; ";

    public TestProjectEFDbContext() { }
    public TestProjectEFDbContext(DbContextOptions options) : base(options) { }

    public DbSet<University> Universities { get; set; }
    public DbSet<MedicineUniversity> MedicineUniversities { get; set; }
    public DbSet<ArtUniversity> ArtUniversities { get; set; }
    public DbSet<TechUniveristy> TechUniveristies { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)

var FirstUniversity = testProjectEFDbContext.Universities.First(); // throws an error
3/23/2020 8:28:43 AM

Accepted Answer

The InvalidOperationException: Sequence contains no elements When appeared that you have not any records in the mapped table.

enter image description here

And it is disappeared when you use FirstOrDefault() extension method.

So, double-check the database and table that you are using in the connection string and you have checked that have records.

Also, beware of Table Attribute: [Table(string name, Properties:[Schema = string])

3/23/2020 9:32:41 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow