数据 reader 与指定不兼容。数据 reader 中没有对应的同名列

data reader is incompatible with the specified. does not have a corresponding column in the data reader with the same name

我不断收到以下异常。这个例外让我感到困惑,因为我不是 selecting UserID.

我尝试将 select 更改为 SELECT *,但这只会导致 result.Count 为 0,无论数据是否存在。

我在数据库中有一个名为 bob tob 的虚拟记录。

我注意到如果我将鼠标悬停在 db.Users.SqlQuery 的用户部分。

里面的文字是

{SELECT 
[Extent1].[userID] AS [userID], 
[Extent1].[userFirstName] AS [userFirstName], 
[Extent1].[userLastName] AS [userLastName], 
[Extent1].[userName] AS [userName], 
[Extent1].[userEmail] AS [userEmail], 
[Extent1].[userPassword] AS [userPassword], 
[Extent1].[userStatus] AS [userStatus], 
[Extent1].[userEmailVerificationStatus] AS [userEmailVerificationStatus], 
[Extent1].[userActivationCode] AS [userActivationCode]
FROM [dbo].[Users] AS [Extent1]}

我猜它正试图 SELECT 所有用户 class 项目而不顾一切?如果那是真的那么我该如何阻止呢?我错过了什么?

这是例外情况:

The data reader is incompatible with the specified 'UserRegistrationPasswordsModel.User'. A member of the type, 'userID', does not have a corresponding column in the data reader with the same name.

下面是调用EmailExists的代码。我错误地添加了 ToString(),希望这可能是问题所在。

#region EmailExist
// Email already exists?
if (Utilities.EmailExists(user.userEmail.ToString()))
{
    // A pretty awesome way to make a custom exception
    ModelState.AddModelError("EmailExist", "Email already exists");

    // Bounce back
    return View(user);
}
#endregion

下面是检查电子邮件是否存在的程序。

#region EmailExists
    // Confirm if the Email exists or not
    public static bool EmailExists(string Email)
    {
        bool result = false;
        Models.UserRegistrationPasswordsEntities1 db = new Models.UserRegistrationPasswordsEntities1();
        var queryResult = db.Users.SqlQuery("SELECT userEmail FROM Users WHERE userEmail = @1;", 
                                                                          new SqlParameter("@1", Email)).FirstOrDefault();

        // the ternary opertor is pretty awesome
        result = queryResult.Result.GetType() == null ? false : true;

        return result;
    }
    #endregion

这是 table 结构:

CREATE TABLE [dbo].[Users]
(
    [userID]                      INT              IDENTITY (1, 1) NOT NULL,
    [userFirstName]               VARCHAR (50)     NOT NULL,
    [userLastName]                VARCHAR (50)     NOT NULL,
    [userName]                    VARCHAR (50)     NOT NULL,
    [userEmail]                   VARCHAR (50)     NOT NULL,
    [userPassword]                VARCHAR (100)    NOT NULL,
    [userStatus]                  BIT              DEFAULT ((0)) NOT NULL,
    [userEmailVerificationStatus] BIT              DEFAULT ((0)) NOT NULL,
    [userActivationCode]          UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
    [userDateOfBirth]             DATETIME         NOT NULL,

    PRIMARY KEY CLUSTERED ([userID] ASC)
);

这是 User 模型 class:

public partial class User
{
    public int userID { get; set; }

    [Display(Name = "First Name")]
    [DataType(DataType.Text)]
    [Required(AllowEmptyStrings = false, ErrorMessage ="First name required")]
    public string userFirstName { get; set; }

    [Display(Name = "Last Name")]
    [DataType(DataType.Text)]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Last name required")]
    public string userLastName { get; set; }

    [Display(Name = "Username")]
    [DataType(DataType.Text)]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Username required")]
    public string userName { get; set; }

    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    [Required(AllowEmptyStrings = false, ErrorMessage = "email is required")]
    public string userEmail { get; set; }

    [Display(Name = "Date Of Birth")]
    [DataType(DataType.DateTime)]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Date of Birth is required")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime userDateOfBirth { get; set;}


    [Display(Name = "Password")]
    [DataType(DataType.Password)]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Password is required")]
    [MinLength(6, ErrorMessage = "Minimum of 6 characters required")]
    public string userPassword { get; set; }

    [Display(Name = "Confirm Password")]
    [DataType(DataType.Password)]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm password is required")]
    [Compare("userPassword", ErrorMessage = "Confirm password and password do not match")]
    public string userConfirmPassword { get; set; }

    public bool userStatus { get; set; }
    public bool userEmailVerificationStatus { get; set; }

    public System.Guid userActivationCode { get; set; }
}

我花了 2 个小时的大部分时间试图解决这个问题。

以下是我为寻找解决方案而访问过的资源。

感谢您提供的任何帮助。

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/advanced-entity-framework-scenarios-for-an-mvc-web-application

https://forums.asp.net/t/1991176.aspx?The+data+reader+is+incompatible+with+the+specified+model

Incompatible Data Reader Exception From EF Mapped Objects

The data reader is incompatible with the specified Entity Framework

https://forums.asp.net/t/1980259.aspx?I+get+this+error+The+data+reader+is+incompatible+with+the+specified+DBLaxmiTatkalModel+TblAttendence+A+member+of+the+type+AttendenceId+does+not+have+a+corresponding+column+in+the+data+reader+with+the+same+name+

错误说:

A member of the type, 'userID', does not have a corresponding column in the data reader with the same name.

这意味着您的查询 return 的结果与您的实体类型 (User) 不匹配。事实上他们没有 - 你的查询 return 单列 userEmail,而类型 User 有更多的列(包括错误消息中提到的 userID )。为什么结果应该匹配类型 User?因为您正在通过 db.Users.SqlQuery.

查询此实体

你的查询也是错误的(因为 '@1' 不是参数而是文字字符串),但这没关系,因为你不需要在这里使用原始 sql 查询。只需做:

public static bool EmailExists(string Email)
{        
    using (var db = new Models.UserRegistrationPasswordsEntities1()) {
        return db.Users.Any(c => c.userEmail == Email);
    }       
}

如果您想发出任意 sql 查询(虽然我要再次声明,在这种情况下绝对没有理由这样做)- 使用 db.Database.SqlQuery:

using (var db = new Models.UserRegistrationPasswordsEntities1()) {
    var email = db.Database.SqlQuery<string>(
        "SELECT userEmail FROM Users WHERE userEmail = @email",
        new SqlParameter("email", Email))
    .FirstOrDefault();
    ...
}