如何在带有实体框架核心1

如何在带有实体框架核心1

本文介绍了如何在带有实体框架核心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脚手架命令当前无法识别或生成视图,我想要一个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.)

注意:我实际上要使用View的原因是出于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 );
    });
}

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

08-30 01:01