ca9163d9
ca9163d9

Reputation: 29159

DbSet<MyModel> property got null value when there is no physical table of MyModel?

(.Net core 3.1)

I have a model class. And I want to fill a list of the model class with data read from a SQL query. There is no physical table with name of MyModel.

public class MyModel { 
    string A { get; set; }
    string B { get; set; }
    string C { get; set; }
}

And the following DbContext class

public calss MyDbContext : DbContext
{
    public DbSet<MyModel> MyModels { get; }

    public IEnumerable<MyModel> GetSomeValue(int x)
    {
       foreach (var i in MyModels.FromSqlRaw(sql)) // MyModels is always null
       {
       }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Ignore<MyModel>();
        modelBuilder.Entity<MyModel>().HasKey(x => new { x.A, x.B });
    }
}

However, the property MyModels is always null and thus MyModels.FromSqlRaw() got error. How to run raw sql to fill the MyModels with values from the database?

Upvotes: 0

Views: 40

Answers (1)

ca9163d9
ca9163d9

Reputation: 29159

It turns out public DbSet<MyModel> MyModels { get; } cannot be readonly. Adding set; resolved the problem.

Upvotes: 1

Related Questions