简体   繁体   English

Scaffold-DbContext SQL 视图? ASP 网络核心 3.1

[英]Scaffold-DbContext SQL Views ? ASP NET CORE 3.1

I need your help.我需要你的帮助。 I read on the web that there has never been a proper way to import views from sql into our asp.net core project.我在网上读到,从来没有一种正确的方法可以将 sql 中的视图导入到我们的 asp.net 核心项目中。 Do you know if in version 3.1 you can do ?你知道在 3.1 版本中你能不能做到? If so, how?如果是这样,如何? For tables I use the "scaffold-DbContext" command.对于表,我使用“scaffold-DbContext”命令。 Thank you very much!非常感谢!

Although you cannot use scaffold-DbContext for database view but you can still use SQL View in your .Net Core project.尽管您不能将 scaffold-DbContext 用于数据库视图,但您仍然可以在 .Net Core 项目中使用 SQL 视图。

Suppose you have the following SQL View假设您有以下 SQL 视图

CREATE VIEW [dbo].[v_MyTableResult] AS

SELECT 
    SELECT Id, Name FROM MyTable

GO

Create a new Model class based on the result set of SQL View.根据 SQL View 的结果集创建一个新的 Model 类。

public class MyTableModel
{
    public int Id { get; set; }
    public string Name { get; set; }
}

In the database context class, introduce property for the Model.在数据库上下文类中,为模型引入属性。

public virtual DbSet<MyTableModel> MyTableResults { get; set; }

In OnModelCreating method, configure model properties在 OnModelCreating 方法中,配置模型属性

    modelBuilder.Entity<MyTableModel>(entity =>
    {
        entity.HasNoKey();

        entity.Property(e => e.Id)
            .HasColumnName("Id");

        entity.Property(e => e.Name)
            .HasColumnName("Name");
    });

Finally, in the method where you need results from the view, call FromSqlRaw on DbSet property最后,在需要视图结果的方法中,在 DbSet 属性上调用 FromSqlRaw

    var myTableResults =
        this.MyDbContext.MyTableResults.FromSqlRaw(
            "SELECT * FROM dbo.v_MyTableResult").ToList();

It seems not supported yet.好像还不支持。 For a workaround, you could refer to有关解决方法,您可以参考

Is it possible to automatically map a DB view on Entity Framework Core version 2.1? 是否可以在 Entity Framework Core 2.1 版上自动映射数据库视图?

It is possible to scaffold a view.可能的脚手架视图。 Just use -Tables the way you would to scaffold a table, only use the name of your view.只需像搭建表一样使用 -Tables,只使用视图的名称。 Eg, If the name of your view is 'vw_inventory', then run this command in the Package Manager Console (substituting your own information for "My..."):例如,如果您的视图名称是“vw_inventory”,则在包管理器控制台中运行此命令(将您自己的信息替换为“我的...”):

PM> Scaffold-DbContext "Server=MyServer;Database=MyDatabase;user id=MyUserId;password=MyPassword" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Temp -Tables vw_inventory

This command will create a model file and context file in the Temp directory of your project.此命令将在项目的 Temp 目录中创建模型文件和上下文文件。 You can move the model file into your models directory (remember to change the namespace name).您可以将模型文件移动到您的模型目录中(记得更改命名空间名称)。 You can copy what you need from the context file and paste it into the appropriate existing context file in your project.您可以从上下文文件中复制您需要的内容并将其粘贴到项目中相应的现有上下文文件中。

Note: If you want to use your view in an integration test using a local db, you'll need to create the view as part of your db setup.注意:如果您想在使用本地数据库的集成测试中使用您的视图,您需要将视图创建为数据库设置的一部分。 If you're going to use the view in more than one test, make sure to add a check for existence of the view.如果您要在多个测试中使用该视图,请确保添加对视图存在的检查。 In this case, since the SQL 'Create View' statement is required to be the only statement in the batch, you'll need to run the create view as dynamic Sql within the existence check statement.在这种情况下,由于 SQL 'Create View' 语句需要是批处理中的唯一语句,因此您需要在存在检查语句中将创建视图作为动态 Sql 运行。 Alternatively you could run separate 'if exists drop view…', then 'create view' statements, but if multiple tests are running concurrently, you don't want the view to be dropped if another test is using it.或者,您可以运行单独的“如果存在删除视图...”,然后运行“创建视图”语句,但如果多个测试同时运行,您不希望在另一个测试正在使用视图时删除该视图。 Example:例子:

  void setupDb() {
    ...
    SomeDb.Command(db => db.Database.ExecuteSqlRaw(CreateInventoryView()));
    ...
  }
  public string CreateInventoryView() => @"
  IF OBJECT_ID('[dbo].[vw_inventory]') IS NULL
    BEGIN EXEC('CREATE VIEW [dbo].[vw_inventory] AS
       SELECT ...')
    END";

This is a helpful link.这是一个有用的链接。 It describes adding the code sections by hand (as Nouman mentioned) instead of scaffolding them: https://docs.microsoft.com/en-us/ef/core/modeling/keyless-entity-types?tabs=fluent-api它描述了手动添加代码部分(如 Nouman 提到的)而不是搭建它们: https ://docs.microsoft.com/en-us/ef/core/modeling/keyless-entity-types?tabs=fluent-api

Yes, we can use scaffold-DbContext with view .是的,我们可以将scaffold-DbContext 与 view 一起使用

using scaffold-DbContext for database view (myview).使用 scaffold-DbContext 进行数据库视图 (myview)。 I executed below scaffold-DbContext query.我在脚手架-DbContext 查询下执行。

Scaffold-DbContext "Data Source=my_server,1433;Initial Catalog=my_database;User Id=my_user;Password=my_password;" Scaffold-DbContext“数据源=my_server,1433;初始目录=my_database;用户ID=my_user;密码=my_password;” Microsoft.EntityFrameworkCore.SqlServer -o Entities -Context ContextName -t myview -f Microsoft.EntityFrameworkCore.SqlServer -o 实体 -Context ContextName -t myview -f

Once you execute then you will get entity class and contextfile.执行后,您将获得实体类和上下文文件。

Code in entity class (myview.cs)实体类 (myview.cs) 中的代码

////// Fetching data
public partial class myview
{ 
    public Guid property_1 { get; set; }
    
}

Code in dbcontect file (ContextName.cs) dbcontect 文件(ContextName.cs) 中的代码

public partial class ContextName : DbContext
{
    public virtual DbSet<myview> myview { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<myview>(entity =>
        {
            entity.HasNoKey();

            entity.ToView("myview", "ExtIntDWFS");

            ////// other property configuration.
        }
    }
}

Code in controller to fetch view data控制器中获取视图数据的代码

////// Fetching data
public async Task<myview> GetView(Base @base)
    {
        myview obj = new myview();

        using (ContextName context = new ContextName())
        {
            obj = await context.myview.Select(s => new myview
                                              {
                                                  property_1 = s.property_1,
                                              }).FirstOrDefaultAsync();
        }

        return obj;
    }

Above code is working for me successfully.上面的代码成功地为我工作。

I recently had a similar need (retrieve one ore more views and create the corresponding classes in a .NET project).我最近有一个类似的需求(检索一个或多个视图并在 .NET 项目中创建相应的类)。 It can be done with Scaffold-DbContect , for example:可以使用Scaffold-DbContect来完成,例如:

Scaffold-DbContext "Server=<address>;
Database=<dbname>;
Trusted_Connection=True" 
Microsoft.EntityFrameworkCore.SqlServer -OutputDir
ModelDirectory -t <table_name> -t <view_name>

It creates a folder called OutputDir with the corresponding classes for the indicated tables or views它创建一个名为OutputDir的文件夹, OutputDir包含指定表或视图的相应类

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

相关问题 使用Scaffold-DbContext时的ASP.NET Core Error - ASP.NET Core Error while using Scaffold-DbContext 在ASP.NET Core中支撑现有数据库(Scaffold-DbContext) - Scaffolding existing databases in ASP.NET Core (Scaffold-DbContext) Scaffold-DbContext 在 .net 核心中抛出错误“找不到程序集” - Scaffold-DbContext throws error “Could not find assembly” in .net core EF Core 脚手架-dbcontext 自定义命名空间 - EF Core scaffold-dbcontext custom namespace EF core 3.1+Pomelo Scaffold-DbContext 防止视图代码生成 - EF core 3.1+Pomelo Scaffold-DbContext prevent view code generation 无法将“System.DBNull”类型的对象转换为 Scaffold-DbContext .Net Core 中的“System.String”类型 - Unable to cast object of type 'System.DBNull' to type 'System.String' in Scaffold-DbContext .Net Core 仅在 EF Core 中的 Scaffold-DbContext 存储过程 - Scaffold-DbContext Stored Procedures only in EF Core 尝试 Scaffold-DbContext 的问题 - Issue trying to Scaffold-DbContext Scaffold-DbContext:找不到命令 - Scaffold-DbContext: command not found Scaffold-DbContext 失败。 System.TypeLoadException:无法在 .NET Core 上加载类型“Microsoft.EntityFrameworkCore.Internal.ProductInfo” - Scaffold-DbContext Fails. System.TypeLoadException: Could not load type 'Microsoft.EntityFrameworkCore.Internal.ProductInfo' on .NET Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM