我正在尝试将基本的 LINQ 查询放入 asp.net 核心上的简单 mvc 中,但在哪里放置(var context

本文关键字:mvc 简单 var context 在哪里 核心 asp 查询 LINQ net | 更新日期: 2023-09-27 17:57:10

1.我是编程新手,在 c# 和 asp.net 核心方面也很新。在本教程之后,我得到了带有链接"博客"数据库的简单MVC项目。所以,现在我的视图索引.cshtml文件代码是:

@model IEnumerable<EFGS.Models.Blog>
@{
    ViewBag.Title = "MealOperators";
}
<h2>Blogs</h2>
<p>
    <a asp-controller="MealOperators" asp-action="Create">Create New</a>
</p>

<table class="table">
    <tr>
        <th>Id</th>
        <th>Url</th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.BlogId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Url)
            </td>
        </tr>
    }
</table>

现在我想学习如何从数据库中获取简单的数据(单个实体)并将其显示在视图中(在我的本地页面 http://localhost:12345/blogs)。例如,如何使用BlogId=5显示博客的 URL 是什么。我找到这个例子是为了上述目的:https://docs.efproject.net/en/latest/querying/basic.html#loading-a-single-entity

根据它,我必须使用这个语句:

using (var context = new BloggingContext())
{
    var blog = context.Blogs
        .Single(b => b.BlogId == 5);
}

但是,对不起我的愚蠢,我不明白把它放在哪里。如果我把它放在Index.cshtml中,我会得到:

找不到类型或命名空间名称"博客上下文"...

如果我放这样的东西:

@namespace EFGetStarted.AspNetCore.ExistingDb.Models{}

@using EFGetStarted.AspNetCore.ExistingDb.Models

@using EFGetStarted.AspNetCore.ExistingDb.Controllers

我仍然收到其他错误。

您能否给我一些关于良好 asp.net 核心模板/源代码的良好链接,我可以找到基本查询,而不是部分像上面的链接/示例,而是在整个项目中,以便我可以跟踪和理解要放什么和放在哪里,什么链接和与什么相关。

阿拉伯数字。而且,顺便说一句,我在哪里可以更深入地阅读和理解上面示例中的@model、模型和模型项是什么?我在问,因为当我尝试自己制作类似的 mvc 项目时,我总是得到

NullReferenceException:对象引用未设置为对象的实例

错误,不明白我应该如何解决它。谢谢!

更新:博客控制器:

using EFGetStarted.AspNetCore.ExistingDb.Models;
using Microsoft.AspNetCore.Mvc;
using System.Linq;
using System;
namespace EFGetStarted.AspNetCore.ExistingDb.Controllers
{
    public class BlogsController : Controller
    {
        private BloggingContext _context;
        public BlogsController(BloggingContext context)
        {
            _context = context;
        }
        public IActionResult Index()
        {
              return View(_context.Blog.ToList());

            //using (var context = new BloggingContext())
            //{
            //    var blogs = from x in context.Blog select x;
            //    return View(blogs.ToArray());
            //}

        }
        private IActionResult View(Func<Blog[]> toArray)
        {
            throw new NotImplementedException();
        }
        public IActionResult Create()
        {
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Blog blog)
        {
            if (ModelState.IsValid)
            {
                _context.Blog.Add(blog);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(blog);
        }
    }
}

博客上下文:

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
namespace EFGetStarted.AspNetCore.ExistingDb.Models
{
    public partial class BloggingContext : DbContext
    {
        public BloggingContext(DbContextOptions<BloggingContext> options)
             : base(options)
        { }
        public BloggingContext()
        {
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>(entity =>
            {
                entity.Property(e => e.Url).IsRequired();
            });
            modelBuilder.Entity<Post>(entity =>
            {
                entity.HasOne(d => d.Blog)
                    .WithMany(p => p.Post)
                    .HasForeignKey(d => d.BlogId);
            });
        }
        public virtual DbSet<Blog> Blog { get; set; }
        public virtual DbSet<Post> Post { get; set; }
    }
}

博客.cs

using System;
using System.Collections.Generic;
namespace EFGetStarted.AspNetCore.ExistingDb.Models
{
    public partial class Blog
    {
        public Blog()
        {
            Post = new HashSet<Post>();
        }
        public int BlogId { get; set; }
        public string Url { get; set; }
        public string Promo { get; set; }
        public virtual ICollection<Post> Post { get; set; }
    }
}

更新:

启动.cs

    using EFGetStarted.AspNetCore.ExistingDb.Models;
    using Microsoft.EntityFrameworkCore;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Logging;
    namespace EFGetStarted.AspNetCore.ExistingDb
    {
        public class Startup
        {
            public Startup(IHostingEnvironment env)
            {
                var builder = new ConfigurationBuilder()
                    .SetBasePath(env.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                    .AddEnvironmentVariables();
                Configuration = builder.Build();
            }
            public IConfigurationRoot Configuration { get; }
            public void ConfigureServices(IServiceCollection services)
            {
                var connection = @"Server=(localdb)'mssqllocaldb;Database=Blogging;Trusted_Connection=True;";
                services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
                string connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
                services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connectionString));  
                services.AddMvc();
            }
            public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
            {
              loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                    app.UseBrowserLink();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                }
                app.UseStaticFiles();
                app.UseMvc(routes =>
                {
                    routes.MapRoute(
                        name: "default",
                        template: "{controller=Home}/{action=Index}/{id?}");
                });
            }
        }
    }

我正在尝试将基本的 LINQ 查询放入 asp.net 核心上的简单 mvc 中,但在哪里放置(var context

在 aspnetcore 中,MVC 的最佳起点是

https://docs.asp.net/en/latest/mvc/index.html

如果您下载Visual Studio社区,MVC项目模板将为您提供一个基本结构,您可以从"填补空白"开始

对您的问题的一般答案是,linq 代码很可能存在于 Controller 类中,该类将负责处理请求、构造模型(像您一样使用 linq)并将其传递给视图(这就是您那里的内容)。

用于演示的示例控制器:

[Authorize]
public class BlogsController : Controller
{
    private readonly BloggingContext _context;
    public BlogsController(BloggingContext context) {
        _context = context;
    }
    public IActionResult Index()
    {
        var blogs = from x in _context.Blog select x;
        return View(blogs.ToArray());            
    }
}

这假设您在 [projroot]''Controllers'' 文件夹中有BlogsController,而 Index.cshtml 位于 [projroot]''View''Blogs'' 文件夹中。

此代码返回所有博客,因为您的视图@model需要IEnumerable Blog

要注入 BloggingContext,您需要在启动时将其添加为服务.cs在 ConfigureServices 方法中:

string connectionString = Configuration["Data:DefaultConnection:ConnectionString"];
services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connectionString));

在 AppSettings.json 中,表示该连接字符串的节点,例如:

  "Data": {
    "DefaultConnection": {
      "ConnectionString": "data source=(local)''SQLEXPRESS;initial catalog=<your_db_name>;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"
    }
  }