如何在带有 Entity Framework Core 1.0 (EF7) 的脚手架 DbContext 中使用数据库视图 [英] How can I use database Views in a scaffolded DbContext with Entity Framework Core 1.0 (EF7)

查看:24
本文介绍了如何在带有 Entity Framework Core 1.0 (EF7) 的脚手架 DbContext 中使用数据库视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

不幸的是,Entity Framework Core 1.0(以前称为 Entity Framework 7)尚不支持视图,我正在尝试使用表来伪造"它.

Unfortunately Entity Framework Core 1.0 (formerly Entity Framework 7) does not yet support Views, and I'm trying to 'fake' it using a table.

然而,脚手架 dotnet dbcontext ef scaffold 命令当前无法识别或生成视图,我想要一个允许查询视图和更新表的 DbContext.有没有办法做到这一点?

However the scaffolding dotnet dbcontext ef scaffold command doesn't currently recognize or generate views, and I want a single DbContext which allows querying a view and updating of tables. Is there a way to do this?

这是我用来搭建 DbContext 的命令:

This is the command I use to scaffold the DbContext:

dotnet ef dbcontext scaffold -c MyStoreContext -o Model "Data Source=(local);Initial Catalog=DBNAME;Integrated Security=True" Microsoft.EntityFrameworkCore.SqlServer --force

(这会将我所有的模型类放在 Model 目录中,并强制覆盖它们.)

(This puts all my model classes in a Model directory, and forces them to be overwritten.)

注意:我实际上想使用视图的原因是用于 GROUP BY 逻辑,EF Core 1.0 也不支持该逻辑

Note: The reason I actually want to use a View is for GROUP BY logic, which isn't supported either in EF Core 1.0

推荐答案

对我来说,我的视图在不同的模式中,所以我不得不改变模型类的一个属性:

For me, my view was in a different schema, so I had to alter an attribute on the model class:

using System.ComponentModel.DataAnnotations.Schema;

namespace API.DataAccess
{
    [Table("MyViewName", Schema = "SomeSchema")]
    public class MyViewName
    {
       //props
    }
}

为了完整性,实体代码:

For completeness, the entity code:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyViewName>(entity =>
    {
        entity.HasKey(e => new { e.SomeColumn }).HasName("PK_FAKEKEY");
            entity.Property(e => e.SomeColumn ).IsRequired();
            entity.Property(e => e.SomeColumn2 );
            entity.Property(e => e.SomeColumn3 );
    });
}

这篇关于如何在带有 Entity Framework Core 1.0 (EF7) 的脚手架 DbContext 中使用数据库视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆