question

6666666 avatar image
0 Votes"
6666666 asked DanielZhang-MSFT commented

How to get the data of the sql to entityframeworkcore?

There is a class:

 public MyClassA
 {
     public int Total{get;set;}
     public  int DeviceNo{get;set;}
    
 }

the sql is
select count(1) Total,DeviceNo from tmp group by DeviceNo
but the MyClassA is no in the DbSet

there is no a DbSet<MyClassA> in the dbcontext.

how to use entityframeworkcore to get the List<MyClassA>()?

dotnet-entity-framework-core
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

No There is no table named tmp.

I want to query to database using sql and get the result which the there is no such table or column in database like count(1) As total.


but I have to create such Class MyClassA but I do not want to migrate it to the database. do you understand?

0 Votes 0 ·

Hi @6666666,
Thanks for your explanation.With EF Core, data access is performed using a model. A model is made up of entity classes and a context object that represents a session with the database.
Once a model is created, it is necessary to use EF Migrations to create a database from the model.
So you can't query to database without migrations.
Best Regards,
Daniel Zhang

0 Votes 0 ·

1 Answer

DanielZhang-MSFT avatar image
0 Votes"
DanielZhang-MSFT answered DanielZhang-MSFT commented

Hi 6666666,
If you want to use entityframeworkcore to get the List<MyClassA>(), you need to define a context class and entity classes that make up the model.

  public class yourContext : DbContext
     {
         public DbSet<MyClassA> myClassA { get; set; }
     }

Then using FromSqlRaw to begin a LINQ query based on a raw SQL query.
More details please refer to the following documents.
Getting Started with EF Core
Raw SQL Queries
Best Regards,
Daniel Zhang*
If the response is helpful, please click "Accept Answer" and upvote it.

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.


· 8
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Can I add [NotMappded] attribute to this MyClassA`?

0 Votes 0 ·

Hi @6666666,
The NotMapped attribute is used to specify that an entity or property is not to be mapped to a table or column in the database.
If you add [NotMappded] attribute to your MyClassA, the MyClassA class will not be mapped to a table in the database.
Best Regards,
Daniel Zhang


0 Votes 0 ·

Then What should I do If I want add it in the dbset but do not want to migrate to database

let me explain.

I want to the MyClassA in the DbSet

public DbSet<MyClassA>MyClassA{get;set;}

but do not want it to add to database as a table.

0 Votes 0 ·
Show more comments