【问题标题】:SQL Query returns two columns but DataSet only contains one and says the other does not existSQL 查询返回两列,但 DataSet 只包含一列,并说另一列不存在
【发布时间】:2020-11-07 14:21:34
【问题描述】:

我有以下代码执行存储过程并返回结果以填充下拉列表。

private DataSet GetData(string SPName, SqlParameter SPParameter)
{
        string CS = ConfigurationManager.ConnectionStrings["HMT2DBCS"].ConnectionString;

        using (SqlConnection con = new SqlConnection(CS))
        {
            SqlDataAdapter da = new SqlDataAdapter(SPName, con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            if (SPParameter != null)
            {
                da.SelectCommand.Parameters.Add(SPParameter);
            }

            con.Open();

            DataSet DS = new DataSet();
            da.Fill(DS);

            con.Close();

            return DS;
        }
}

public void PopulateTicket()
{
        DataSet DS = GetData("spGetTickets", null);
        ddlTicket.DataSource = DS;
        ddlTicket.DataTextField = "TicketInfo";
        ddlTicket.DataValueField = "MicroBT_ticket";
        ddlTicket.DataBind();

        ListItem liticket = new ListItem("--Select a ticket--", "-1");
        ddlTicket.Items.Insert(0, liticket);
}

执行此操作时出现此错误:

System.Web.HttpException: 'DataBinding: 'System.Data.DataRowView' 不包含名为 'TicketInfo' 的属性。'

当我从 SSMS 运行存储过程时,我得到以下结果表,其中包含列 TicketInfo

我已经仔细检查了所有列和字段的拼写。我在另一台 PC 上有一个 VS 项目的副本和一个重复的“测试”数据库设置,并且相同的代码在那里工作正常!我不知道是什么引发了这个错误。

更新:数据集可视化工具在我的数据集中显示以下内容,TicketInfo 列由于某种原因丢失:

【问题讨论】:

  • 我鼓励您使用像实体框架这样的 ORM。使处理数据集变得更加容易。
  • 就在上面一行:“return DS;”,你能运行一些类似的代码:DS.WriteXml(@"c:\temp\result.xml", System.Data.XmlWriteMode.WriteSchema) ;这会将数据集的内容写入文件。如果您将 xml 文件中的内容粘贴到您的帖子中,我们可以更轻松地看到发生了什么。如果目录 c:\temp 不存在,则必须事先创建它(或使用您的应用程序具有写入权限的另一个目录)。
  • ...当然,不要发布文件中的任何敏感信息 - 您可以将敏感部分替换为 XXX 或其他内容。

标签: c# sql-server ado.net


【解决方案1】:

关于我在评论中提到的 ORM。这是一个关于如何为实体框架定义一个类(代码优先)的示例,您可以很容易地从数据库表中进行逆向工程。 Entity Framework 会为您做到这一点。

下面是我之前在此论坛上发布的另一个问题的示例。您可以看到使用 LINQ 从数据库中的表中检索数据是多么容易,您还可以做更多事情。

namespace ToPagedList
{
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;

    [Table("Course")]
    public partial class Course
    {
        public int CourseId { get; set; }

        public int? CourseGroupId { get; set; }

        [StringLength(50)]
        public string CourseCode { get; set; }

        [Required]
        [StringLength(100)]
        public string Title { get; set; }

        [StringLength(1000)]
        public string ShortDescription { get; set; }

        [Column(TypeName = "ntext")]
        [Required]
        public string Contents { get; set; }

        [Column(TypeName = "ntext")]
        public string MailTextApplied { get; set; }

        [Column(TypeName = "ntext")]
        public string MailTextAccepted { get; set; }

        [Column(TypeName = "ntext")]
        public string MailTextRejected { get; set; }

        [Column(TypeName = "ntext")]
        public string MailTextDeleted { get; set; }

        [StringLength(1000)]
        public string ExternalRegistrationUrl { get; set; }

        public bool Visible { get; set; }

        [StringLength(1000)]
        public string ExternalCourseUrl { get; set; }

        public string Reviews { get; set; }

        [StringLength(50)]
        public string School { get; set; }

        [Column(TypeName = "ntext")]
        public string MailTextCertified { get; set; }

        [Column(TypeName = "ntext")]
        public string MailTextNoShow { get; set; }

        [Column(TypeName = "ntext")]
        public string MailTextPassed { get; set; }

        [Column(TypeName = "ntext")]
        public string MailTextPartlyCompleted { get; set; }

        [Column(TypeName = "ntext")]
        public string MailTextWaitingList { get; set; }

        [Column(TypeName = "ntext")]
        public string MailTextWithdrawn { get; set; }

        public bool ShowFromStartDate { get; set; }
    }
}

这是检索数据的代码:

using System;
using System.Diagnostics;

namespace ToPagedList
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();

            var list1 = Repository.GetCourses1();

            sw.Stop();
            Console.WriteLine($"Getting list 1 took {sw.ElapsedMilliseconds} milliseconds");


            sw.Reset();
            sw.Start();

            var list2 = Repository.GetCourses2();

            sw.Stop();
            Console.WriteLine($"Getting list 2 took {sw.ElapsedMilliseconds} milliseconds");

            Console.ReadKey();
        }
    }
}

还有 Repository 类:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ToPagedList
{
    public class Repository
    {
        public static List<DocumentsModel> GetCourses1(string school = null, string code = null, string title = null, int page = 0, int count = 15)
        {
            var courses = new DocumentModelEntities().Course;

            return courses.Where(course => string.IsNullOrEmpty(code) || course.CourseCode.Contains(code))
                                 .Where(course => String.IsNullOrEmpty(title) || course.Title.Contains(title))
                                 .Where(w => String.IsNullOrEmpty(school) || w.School == school)
                                 // From here your table is read from the DB using the where clauses
                                 .Select(s => new DocumentsModel
                                 {
                                     Code = code.Trim(),
                                     Title = s.Title
                                 })
                                 .OrderBy(o => o.Code)
                                 .Skip(page * count)
                                 .Take(count)
                                 .ToList();
        }

        public static List<DocumentsModel> GetCourses2(string school = null, string code = null, string title = null, int page = 0, int count = 15)
        {
            var courses = new DocumentModelEntities().Course;

            return courses.Where(course => string.IsNullOrEmpty(code) || course.CourseCode.Contains(code))
                             .Where(course => String.IsNullOrEmpty(title) || course.Title.Contains(title))
                             .Where(w => String.IsNullOrEmpty(school) || w.School == school)
                             .OrderBy(course => course.CourseCode)
                             .Skip(page * count)
                             .Take(count)
                             // From here your table is read from the DB using the where clauses, order by, skip and take
                             .Select(s => new DocumentsModel
                             {
                                 Code = code.Trim(),
                                 Title = s.Title
                             })
                             .ToList();
        }
    }
}

【讨论】:

    【解决方案2】:

    您需要使用的是DataTable 而不是DataSet,所以您的代码应该是这样的:

    DataTable DT = GetData("spGetTickets", null).Tables[0];
    ddlTicket.DataSource = DT;
    

    【讨论】:

      猜你喜欢
      • 2021-10-24
      • 2020-08-24
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 1970-01-01
      • 2014-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多