简体   繁体   English

在没有 DbSet 的情况下查询 Entity Framework Core

[英]Querying Entity Framework Core Without DbSet

I'm working on a data-driven solution using Entity Framework Core.我正在使用 Entity Framework Core 开发数据驱动的解决方案。 I dynamically create SQL Server tables using ExecuteRawSQL() and build the query string based on the contents of a file I am reading in. I would like to query those tables but I do not have DbSets for them because they were created dynamically.我使用ExecuteRawSQL()动态创建 SQL 服务器表,并根据我正在读取的文件的内容构建查询字符串。我想查询这些表,但我没有它们的 DbSet,因为它们是动态创建的。 I tried using: ExecuteRawSQL("SELECT * FROM...") but this only returns the number of rows affected.我尝试使用: ExecuteRawSQL("SELECT * FROM...")但这仅返回受影响的行数。

Ideally, I would like to get each one of the rows back from this query in the form of Dictionaries (key = column name, value = column value).理想情况下,我希望以字典的形式(键 = 列名,值 = 列值)从此查询中取回每一行。 Any ideas?有任何想法吗? Thanks!谢谢!

In EF Core you can use the DbContext Set<T>() method and then FromRawSql() to retrieve data and translate the results into a domain class that is not registered as a DbSet<T> .在 EF Core 中,您可以使用 DbContext Set<T>()方法,然后FromRawSql()检索数据并将结果转换为未注册为DbSet<T>的域 class 。

In this example, I created a Cat object to represent a row in the Cats table:在这个例子中,我创建了一个 Cat object 来表示 Cats 表中的一行:

public class Cat
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Breed { get; set; }
}

Now EF Core knows how to project the results:现在 EF Core 知道如何投影结果:

var context = new SampleDbContext();

var cats = context
    .Set<Cat>()
    .FromSqlRaw("SELECT * FROM Cats")
    .ToList();

However, you'll have to tell EF Core to map that object to the database table on your DbContext class:但是,您必须将 EF Core 告诉 map object 到DbContext class 上的数据库表:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Cat>().ToTable("Cats");
}

It's also important that the object you're projecting the results to has the exact same properties as the table you're pulling the data from, otherwise you'll get an exception.同样重要的是,您将结果投影到的 object 与您从中提取数据的表具有完全相同的属性,否则您会遇到异常。

I'm not sure how you would format the results as a dictionary, but it's possible to use Select() after FromRawSql() .我不确定如何将结果格式化为字典,但可以在FromRawSql() Select() ) 。

var links = context.Set<Cat>()
    .FromSqlRaw("SELECT * FROM Cats")
    .Select(c =>
        new
        {
            Key = nameof(c.Id),
            Value = c.Id
        });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM