代码之家  ›  专栏  ›  技术社区  ›  Adam Schneider

数据读取器与指定的不兼容。在数据读取器中没有同名的对应列

  •  4
  • Adam Schneider  · 技术社区  · 8 年前

    我一直得到以下例外。这个例外让我困惑,因为我没有选择 UserID

    我已尝试将选择更改为 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]}
    

    我猜它是在尝试选择所有的用户类项目,不管是什么?如果这是真的,那么我该如何阻止这一切?我错过了什么?

    例外情况如下:

    数据读取器与指定的“UserRegistrationPasswordsModel”不兼容。用户'。“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; }
    }
    

    我花了两个小时的大部分时间试图弄明白这一点。

    下面是我试图找到解决方案时访问的资源。

    非常感谢您的任何帮助。

    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 回复  |  直到 8 年前
        1
  •  6
  •   Evk    8 年前

    错误显示:

    “userID”类型的成员没有相应的列 在具有相同名称的数据读取器中。

    这意味着查询返回的结果与实体的类型不匹配( User )。事实上,它们并没有-您的查询只返回一列 userEmail ,while类型 使用者 有更多列(包括 userID 错误消息中提到)。为什么结果应与类型匹配 使用者 ?因为您正在通过以下操作查询此实体 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();
        ...
    }
    
    推荐文章