简体   繁体   English

无法使用 EF Core 从 MS SQL 服务器检索数据

[英]Cannot retrieve data from MS SQL Server using EF Core

I'm using ASP.NET Core 3.1, SQL Server 18, ASP.NET Identity 3.1.9 and EF Core 3.1.9 for a project I'm doing for my University course.我正在使用 ASP.NET Core 3.1、SQL Server 18、ASP.NET Identity 3.1.9 和 EF Core 为我的大学课程 3.1.9 做项目。 For my project I have taken code first approach to create models for database.对于我的项目,我采用代码优先的方法为数据库创建模型。 One of the models is Consultation.其中一种模式是咨询。

Consultation.cs :咨询.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; }
    }
}

I have CRUD Pages for this Model.我有这个 Model 的 CRUD 页面。 Now, in the "Index.cshtml" page, I want to show the consultations that only the "current user" only.现在,在“Index.cshtml”页面中,我想显示的只有“当前用户”的咨询。 "Identity_Number" is the FK in Consultation table to establish relation with the Users table. “Identity_Number”是Consultation表中的FK,用于与Users表建立关系。 The tutorials I followed generated the CRUD pages automatically and I also looked for some more materials in the internet but they weren't that helpful for me.我遵循的教程自动生成了 CRUD 页面,我还在互联网上寻找了更多材料,但它们对我没有太大帮助。

The automatically generated Index.cshtml.cs :自动生成的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();
        }
    }
}

I tried to modify it so I can achieve the data for the Current User only.我尝试对其进行修改,以便仅获取当前用户的数据。

Modified Index.cshtm.cs :修改后的 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; }
        }
    }    
}

The code without Try Catch throws this error:没有Try Catch的代码会抛出这个错误:

NullReferenceException: Object reference not set to an instance of an object. NullReferenceException:Object 引用未设置为 object 的实例。 lambda_method(Closure) lambda_method(闭包)

InvalidOperationException: An exception was thrown while attempting to evaluate a LINQ query parameter expression. InvalidOperationException:尝试评估 LINQ 查询参数表达式时引发异常。 To show additional information call EnableSensitiveDataLogging() when overriding DbContext.OnConfiguring.要在覆盖 DbContext.OnConfiguring 时显示附加信息,请调用 EnableSensitiveDataLogging()。 Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.GetValue(Expression expression, out string parameterName)] Microsoft.EntityFrameworkCore.Query.Internal.ParameterExtractingExpressionVisitor.GetValue(Expression expression, out string parameterName)]

Screenshot: [ 1 ]截图:[ 1 ]

Tried #nullable enable as I thought it was returning exception in case the consultation table was empty, but later when I entered data into table, it was still the same.尝试了#nullable enable ,因为我认为它会在咨询表为空的情况下返回异常,但后来当我将数据输入表时,它仍然是一样的。

I wanted to read current user using Identity core.我想使用身份核心阅读当前用户。 I don't really know if it works that way and also how can I achieve my goal of reading Current Users Consultation Data only?我真的不知道它是否可以这样工作,以及我如何才能实现仅阅读当前用户咨询数据的目标? I'm learning C#, ASP.NET Core and Entity Framework recently.我最近在学习 C#、ASP.NET 核心和实体框架。 So don't know much about them, tried these modifications just out of the blue.所以对它们了解不多,只是突然尝试了这些修改。

Thanks to @PaulCarlton and @Romka, I now know where was the problem.感谢@PaulCarlton 和@Romka,我现在知道问题出在哪里。 Helped me to find solution to this problem.帮助我找到了解决这个问题的方法。 I had to modified my code further:我不得不进一步修改我的代码:

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();  
        }

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

暂无
暂无

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

相关问题 无法使用存储过程从 SQL Server 检索数据 - Cannot retrieve data from SQL Server using Stored Procedure 使用 EF Core 将数据从 Excel 移动到 SQL 服务器数据库的效率建议 - Efficiency Suggestions for Moving Data from Excel to SQL Server Database using EF Core 无法使用 EF Core 执行带有命名和输出参数的 SQL Server SP - Cannot Execute SQL Server SP with Named and output parameters using EF Core 在 Sql 服务器中使用 BYTE 作为标识列类型时,EF 核心“无法为标识列插入显式值” - EF core "cannot insert explicit value for identity column" when using BYTE as identity column type in Sql Server 使用具有基本身份验证的 .NET 获取外部 API,并使用 EF Core 将数据存储在 SQL 服务器数据库中 - Fetch external API using .NET with basic authentication and store data in SQL Server database using EF Core AWS Lambda with.Net Core 3.1 - 使用 EF Core 时 SQL 服务器超时,但工作正常 ADO class Microsoft.Data.SqlClient (SqlConnection) - AWS Lambda with .Net Core 3.1 - Timeout from SQL Server when using EF Core but works fine ADO class Microsoft.Data.SqlClient (SqlConnection) EF Core 无法将数据从旧数据库传输到新 SQL Server 数据库中 - EF Core Fails to transfer data into new SQL Server DB from old one 使用EF / SQL Server进行数据转换转换 - Data transfer with transformation using EF / SQL Server 使用 EF Core 2.2 使用 SQL Server DECRYPTBYKEY 解密字符串 - Using EF Core 2.2 to decrypt a string using SQL Server DECRYPTBYKEY 使用SilverLight从SQL Server 2008建立连接和检索数据 - Make connection and retrieve data from SQL Server 2008 Using SilverLight
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM