【问题标题】:Cannot retrieve data from MS SQL Server using EF Core无法使用 EF Core 从 MS SQL Server 检索数据
【发布时间】:2021-04-02 05:55:54
【问题描述】:

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

Consultation.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 表中的FK,用于与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,因为我认为如果咨询表为空,它会返回异常,但后来当我将数据输入表时,它仍然是一样的。

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

【问题讨论】:

  • 数据库中有数据吗?在尝试从空对象中提取数据之前,请确保该对象不为空。看起来代码没有在数据库中找到用户。
  • 如果对象“userFromDb”的电子邮件属性为空,您能否在“Consultation = await _context.Consultation.Where....”行使用断点进行调试?
  • 是的。我已经为当前用户插入了数据。当前用户的身份号码在那里。但错误仍然存​​在。
  • 是的“userFromDb”似乎为空。那么如何检索当前用户 Identity_Number 呢? Identity_Number 是我使用 Users 类创建的自定义属性,并将其与 .Net Identity 一起使用。 @Romka
  • #nullable enable 与您的问题无关。可空上下文允许人们通过明确声明一个对象是否可以为空来设计他们的合同(接口)。这是一个设计决定。

标签: c# asp.net-mvc asp.net-core entity-framework-core asp.net-identity


【解决方案1】:

感谢@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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2016-02-29
    • 2013-06-27
    • 2014-08-22
    相关资源
    最近更新 更多