简体   繁体   English

通过Entity Framework Core查询SQL中的视图

[英]Querying a view in SQL through Entity Framework Core

I am trying to query an already existing view in SQL Server which I am connected to in Visual Studio 2019.我正在尝试查询我在 Visual Studio 2019 中连接到的 SQL 服务器中已经存在的视图。

I've created a class corresponding to the name of my Users database called UsersDbContext .:我创建了一个 class 对应于名为UsersDbContext的用户数据库的名称:

 class UsersDbContext : DbContext
    {            
        public DbSet<EventView> Users { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Data Source=REDACTED;User ID=REDACTED;Password=REDACTERD;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
        }
    }

In this database I have a view named eventview.fss .在这个数据库中,我有一个名为eventview.fss的视图。 How do I access the data from here from Entity Framework?如何从 Entity Framework 访问此处的数据?

In my main class where I want to process the data:在我要处理数据的主要 class 中:

private static readonly UsersDbContext _context = new UsersDbContext();

var myid = _context.Users.FromSqlRaw($"SELECT Id FROM eventview.fss");

In my models class I've added a model for the view.在我的模型 class 中,我为视图添加了 model。 It is very simple:这很简单:

public class EventView
{
    public string Date { get; set; }
    public string Id { get; set; }
}

What am I missing?我错过了什么? Ideally I'd like to have the the rows from the view be put into a List<EventView> then I can work with the data from there.理想情况下,我希望将视图中的行放入List<EventView>然后我可以处理那里的数据。

Edit: when I try to run _context.Users.FromSqlRaw($"SELECT Id FROM eventview.fss").ToList();编辑:当我尝试运行_context.Users.FromSqlRaw($"SELECT Id FROM eventview.fss").ToList(); I get the error for SqlException: Invalid object name eventview.fss我收到 SqlException 的错误:Invalid object name eventview.fss

You can tell EF Core how to retrieve the data set so you don't need to use raw sql.您可以告诉 EF Core 如何检索数据集,这样您就不需要使用原始 sql。 Add a dbset in the context.在上下文中添加一个 dbset。 In OnModelCreating, something like: builder.Entity().HasNoKey().ToView("eventview.fss", "YourSchemaName");在 OnModelCreating 中,类似:builder.Entity().HasNoKey().ToView("eventview.fss", "YourSchemaName");

My problem was that my connection string was missing the Database property.我的问题是我的连接字符串缺少Database属性。 Once I've added it now I can pull the data.一旦我现在添加它,我就可以提取数据。

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

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