数据读取器与指定的不兼容。数据阅读器中没有相应的列具有相同的名称

时间:2018-04-02 04:52:28

标签: c# asp.net asp.net-mvc parameterized-query

我一直得到以下异常。这个例外令我感到困惑,因为我没有选择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]}

我猜他试图选择所有的User类项目,无论如何?如果那是真的那么我该怎么做呢?我错过了什么?

这是一个例外:

  

数据阅读器与指定的&UserRegistrationPasswordsModel.User'不兼容。该类型的成员' userID'在数据阅读器中没有相应的具有相同名称的列。

以下是调用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

这是表结构:

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模型类:

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+

What can cause an EntityCommandExecutionException in EntityCommandDefinition.ExecuteStoreCommands?

1 个答案:

答案 0 :(得分:2)

错误说:

  

该类型的成员'userID'没有相应的列   在具有相同名称的数据阅读器中。

这意味着您的查询返回的结果与您的实体类型(User)不匹配。确实他们没有 - 您的查询返回单列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();
    ...
}