ASP.NET Core 6和SQL Server视图列表 - 不是CRUD

发布于 2025-01-18 23:36:37 字数 3949 浏览 0 评论 0原文

我正在尝试使用 ASP.NET Core 6 从名为 vwSHIPPINGSCHEDULE 的 SQL Server 数据库视图中开发一个简单的 Razor 数据视图。

我没有使用 startup.cs 文件,正如我读到的那样,该方法已过时,我们都应该使用 Program.cs更新:好吧,这里错了。我是 ASP.net Core 的新手。

这是到目前为止我在 Program.cs 中的代码

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SchedulerCore;
using SchedulerCore.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<MovementContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("myConxStr")));

builder.Services.AddControllers();

var app = builder.Build();

我的视图模型:

using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using SchedulerCore.Entities;
using Microsoft.Extensions.Configuration;

namespace SchedulerCore
{
    public partial class MovementContext : DbContext
    {
        public MovementContext()
        {
        }

        public MovementContext(DbContextOptions<MovementContext> options)
            : base(options)
        {
        }

        public virtual DbSet<vwSHIPPINGSCHEDULE> vwSHIPPINGSCHEDULE { get; set; } = null!;

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.UseCollation("Latin1_General_CI_AI");

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

                entity.ToView("vwSHIPPINGSCHEDULE", "POTS");

                entity.Property(e => e.LOA).HasColumnType("numeric(18, 4)");

                entity.Property(e => e.beam).HasColumnType("numeric(18, 4)");

                entity.Property(e => e.cargo).HasMaxLength(4000);

                entity.Property(e => e.country).HasMaxLength(50);

                entity.Property(e => e.details).HasMaxLength(100);

                entity.Property(e => e.duration).HasColumnType("numeric(8, 2)");

                entity.Property(e => e.end_date).HasColumnType("datetime");

                entity.Property(e => e.flag).HasMaxLength(50);

                entity.Property(e => e.sectionID).HasMaxLength(20);

                entity.Property(e => e.shipclass).HasMaxLength(100);

                entity.Property(e => e.start_date).HasColumnType("datetime");

                entity.Property(e => e.stevedore).HasMaxLength(20);

                entity.Property(e => e.text).HasMaxLength(100);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

我的数据访问模型:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using SchedulerCore.Entities;

namespace SchedulerCore.Models
{
    public static class SchedulerInitializerExtension
    {
        public static IHost LoadMovements(this IHost webHost)
        {
            var serviceScopeFactory =
            (IServiceScopeFactory?)webHost.Services.GetService(typeof(IServiceScopeFactory));

            using (var scope = serviceScopeFactory!.CreateScope())
            {
                var services = scope.ServiceProvider;
                var dbContext = services.GetRequiredService<MovementContext>();

                //this is where I am stuck
                //dbContext.Database.EnsureDeleted();
                //dbContext.Database.EnsureCreated();
                //SchedulerSeeder.Seed(dbContext);
            }

            return webHost;
        }
    }
}

我不想像大多数博客谈论的那样实现 CRUD。我只想从 SQL Server 数据库视图生成数据的列表视图。

如何将 sql 视图链接到上述模型? OnModelCreating() 的用途是什么?我使用脚手架创建的,在“欺骗”.Net Core 中从视图为我生成代码。

感谢这里的任何想法。

I am trying to develop a simple Razor view of data from a SQL Server database view called vwSHIPPINGSCHEDULE, using ASP.NET Core 6.

I am not using a startup.cs file, as I've read that method is obsolete and we should all be using Program.cs. UPDATE: ok wrong here. I am new to ASP.net Core.

Here is my code so far in Program.cs

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using SchedulerCore;
using SchedulerCore.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

builder.Services.AddDbContext<MovementContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("myConxStr")));

builder.Services.AddControllers();

var app = builder.Build();

My view model:

using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using SchedulerCore.Entities;
using Microsoft.Extensions.Configuration;

namespace SchedulerCore
{
    public partial class MovementContext : DbContext
    {
        public MovementContext()
        {
        }

        public MovementContext(DbContextOptions<MovementContext> options)
            : base(options)
        {
        }

        public virtual DbSet<vwSHIPPINGSCHEDULE> vwSHIPPINGSCHEDULE { get; set; } = null!;

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.UseCollation("Latin1_General_CI_AI");

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

                entity.ToView("vwSHIPPINGSCHEDULE", "POTS");

                entity.Property(e => e.LOA).HasColumnType("numeric(18, 4)");

                entity.Property(e => e.beam).HasColumnType("numeric(18, 4)");

                entity.Property(e => e.cargo).HasMaxLength(4000);

                entity.Property(e => e.country).HasMaxLength(50);

                entity.Property(e => e.details).HasMaxLength(100);

                entity.Property(e => e.duration).HasColumnType("numeric(8, 2)");

                entity.Property(e => e.end_date).HasColumnType("datetime");

                entity.Property(e => e.flag).HasMaxLength(50);

                entity.Property(e => e.sectionID).HasMaxLength(20);

                entity.Property(e => e.shipclass).HasMaxLength(100);

                entity.Property(e => e.start_date).HasColumnType("datetime");

                entity.Property(e => e.stevedore).HasMaxLength(20);

                entity.Property(e => e.text).HasMaxLength(100);
            });

            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

My Data Access Model:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using SchedulerCore.Entities;

namespace SchedulerCore.Models
{
    public static class SchedulerInitializerExtension
    {
        public static IHost LoadMovements(this IHost webHost)
        {
            var serviceScopeFactory =
            (IServiceScopeFactory?)webHost.Services.GetService(typeof(IServiceScopeFactory));

            using (var scope = serviceScopeFactory!.CreateScope())
            {
                var services = scope.ServiceProvider;
                var dbContext = services.GetRequiredService<MovementContext>();

                //this is where I am stuck
                //dbContext.Database.EnsureDeleted();
                //dbContext.Database.EnsureCreated();
                //SchedulerSeeder.Seed(dbContext);
            }

            return webHost;
        }
    }
}

I don't want to implement a CRUD like most blogs talk about. I just want to generate a List view of the data from my SQL Server database view.

How do I link the sql view to the above model? And what is the OnModelCreating() used for? That I created using scaffolding, in "tricking" .Net Core to generate the code for me from a view.

Thanks for any ideas from here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

木森分化 2025-01-25 23:36:37

您可以使用实体框架数据库第一种方法。要获取SQL视图的模型,您必须踩踏数据库。

这是一个示例代码,可以使用.NET CLI脚打脚本数据库,

dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer

您应该用连接字符串在引号中替换零件。

您的观点将被建模为无钥匙实体。

以下文章提到了如何详细实现这一目标。

https://learn.microsoft.com/en-us/core/what-is-new/ef/ef-core-3.x/#revers-degervers-eendverse-endervers-eendersing-of-database-views

You can use the Entity Framework db first approach. To get the model of your sql view, you have to scaffold the database.

Here is an example code to scaffold the database using the .NET CLI

dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer

You should replace the part within quotes with your connection string.

Your view will be modeled as a keyless entity.

The following article mentions how to achieve this in detail.

https://learn.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.x/#reverse-engineering-of-database-views

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文