首页 > 解决方案 > 无法使用 EF Core 从 MS SQL Server 检索数据

问题描述

我正在为我的大学课程做的一个项目使用 ASP.NET Core 3.1、SQL Server 18、ASP.NET Identity 3.1.9 和 EF Core 3.1.9。对于我的项目,我采用代码优先的方法为数据库创建模型。其中一种模式是咨询。

咨询.cs

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;

namespace National_Healthcare_System.Models
{
    public class Consultation
    {
        [Key]
        [Display(Name = "Consultation ID")]
        public Guid Consultation_Id { get; set; }

        public Guid Doctor_Id { get; set; }

        [Required]
        [Display(Name = "Date and Time")]
        public DateTime Consultation_DateTime { get; set; } = DateTime.Now;

        [Display(Name = "NID/Birth Certificate No.")]
        [StringLength(13, ErrorMessage = "NID/Birth Certificate Number is Invalid Size", MinimumLength = 10)]
        public string Identity_Number { get; set; }

        [Required]
        [Display(Name = "Comment")]
        public string Comment { get; set; }

        [IgnoreDataMember]
        public virtual Doctor Doctor { get; set; }

        public virtual Users Users { get; set; }
    }
}

我有这个模型的 CRUD 页面。现在,在“Index.cshtml”页面中,我想显示的只有“当前用户”的咨询。“Identity_Number”是Consultation表中用于与表建立关系的外键Users。我遵循的教程自动生成了 CRUD 页面,我还在互联网上寻找了更多材料,但它们对我没有太大帮助。

自动生成的Index.cshtml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using National_Healthcare_System.Data;
using National_Healthcare_System.Models;

namespace National_Healthcare_System.Pages.Consultations
{
    public class IndexModel : PageModel
    {
        
        private readonly ApplicationDbContext _context;

        public IndexModel(ApplicationDbContext context)
        {
            _context = context;
        }

        public List<Consultation> Consultation { get; set; }

        public async Task OnGetAsync(Guid id)
        {
            Consultation = await _context.Consultation.ToListAsync();
        }
    }
}

我尝试对其进行修改,以便仅获取当前用户的数据。

修改后的 Index.cshtm.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using National_Healthcare_System.Data;
using National_Healthcare_System.Models;

namespace National_Healthcare_System.Pages.Consultations
{
    public class IndexModel : PageModel
    {
        private readonly ApplicationDbContext _context;
        private readonly UserManager<IdentityUser> _userManager;
        private readonly SignInManager<IdentityUser> _signInManager;

        public IndexModel(UserManager<IdentityUser> userManager,
                          SignInManager<IdentityUser> signInManager,
                          ApplicationDbContext context)
        {
            _userManager = userManager;
            _signInManager = signInManager;
            _context = context;
        }

        #nullable enable
        public List<Consultation> Consultation { get; set; }

        public async Task OnGetAsync(IdentityUser user)
        {
            var userFromDb = await _context.User.FirstOrDefaultAsync(u => u.Email == user.Email);
            try 
            { 
                Consultation = await _context.Consultation.Where(c => c.Identity_Number == userFromDb.Identity_Number).ToListAsync();
            }
            catch { Exception ex; }
        }
    }    
}

没有的代码Try Catch会引发此错误:

NullReferenceException:对象引用未设置为对象的实例。lambda_method(闭包)

InvalidOperationException:尝试计算 LINQ 查询参数表达式时引发异常。要在覆盖 DbContext.OnConfiguring 时显示附加信息,请调用 EnableSensitiveDataLogging()。Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.GetValue(Expression expression, out string parameterName)]

截图:[ 1 ]

尝试了#nullable enable,因为我认为如果咨询表为空,它会返回异常,但后来当我将数据输入表时,它仍然是一样的。

我想使用身份核心阅读当前用户。我真的不知道它是否可以这样工作,以及我如何才能实现仅阅读当前用户咨询数据的目标?我最近在学习 C#、ASP.NET Core 和 Entity Framework。所以对它们了解不多,只是突然尝试了这些修改。

标签: c#asp.net-mvcasp.net-coreentity-framework-coreasp.net-identity

解决方案


感谢@PaulCarlton 和@Romka,我现在知道问题出在哪里。帮助我找到了解决这个问题的方法。我不得不进一步修改我的代码:

public async Task OnGetAsync()
        {
            //this line helped to get current users data from DB
var user = await _userManager.GetUserAsync(HttpContext.User);
            var userFromDb = await _context.User.FirstOrDefaultAsync(u => u.Email == user.Email);
                     Consultation = await _context.Consultation.Where(c => c.Identity_Number == userFromDb.Identity_Number).ToListAsync();  
        }

这个线程很有帮助: stackoverflow: How to get current user in asp.net core


推荐阅读