简体   繁体   English

如何基于 EF Core(无密钥实体)中的查询创建对象?

[英]How do I create objects based on a query in EF Core (keyless entities)?

I am trying to map the results of a complex SQL query to a keyless entity in EF Core.我正在尝试 map 对 EF Core 中的无密钥实体进行复杂的 SQL 查询的结果。 (I basically need to create a view client-side due to having to deal with a preexisting database.) (由于必须处理预先存在的数据库,我基本上需要创建一个视图客户端。)

However, when trying to retrieve my data, I get an InvalidOperationException "Sequence contains no elements".但是,当尝试检索我的数据时,我得到一个 InvalidOperationException “序列不包含元素”。 I can map base tables in the DB to normal entities, so I know the connection string is correct.我可以将数据库中的 map 基表转换为正常实体,所以我知道连接字符串是正确的。 A simplified, but complete example:一个简化但完整的示例:

using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

class Program
{
    static void Main(string[] args)
    {
        using (var db = new QueryDbContext())
        {
            List<Model> result = db.Orders.ToList();  // <-- exception occurs here.
            Console.WriteLine($"Found: {result.Count}");
        }
    }
}

public class Model
{
    public string OrderId { get; }
}

public class QueryDbContext : DbContext
{
    public QueryDbContext()
        : base()
    {}

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            _ = optionsBuilder
                .UseSqlServer("myconnectionstring");
        }
    }

    public DbSet<Model> Orders { get; set; }
    private const string _OrdersSql =
        "select top 5 orderid from tbl_orders order by transacttime desc";

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Model>(m =>
            {
                m.HasNoKey();
                m.ToQuery(() => Set<Model>().FromSqlRaw(_OrdersSql));
            });
    }
}

Set<>() is the current version (since EFCore 3.0) of Query<>() as described in the answer to FromSql with Non-Existing Entity . Set<>()是 Query<>() 的当前版本(自 EFCore 3.0 起),如FromSql with Non-Existing Entity的答案中所述。

The problem was that the model properties need both setters and getters, even though the model is read-only.问题是 model 属性需要 setter 和 getter,即使 model 是只读的。 So the model should be所以 model 应该是

public class Model
{
    public string OrderId { get; set; }
}

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

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