Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/296.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# SQL查询返回两列,但数据集仅包含一列,并表示另一列不存在_C#_Sql Server_Ado.net - Fatal编程技术网

C# SQL查询返回两列,但数据集仅包含一列,并表示另一列不存在

C# SQL查询返回两列,但数据集仅包含一列,并表示另一列不存在,c#,sql-server,ado.net,C#,Sql Server,Ado.net,下面的代码执行一个存储过程并返回结果以填充dropdownlist private DataSet GetData(string SPName, SqlParameter SPParameter) { string CS = ConfigurationManager.ConnectionStrings["HMT2DBCS"].ConnectionString; using (SqlConnection con = new SqlConnect

下面的代码执行一个存储过程并返回结果以填充dropdownlist

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

我仔细检查了所有列和字段的拼写。我有一个副本的VS项目和一个重复的'测试'数据库设置在另一台电脑上,同样的代码在那里工作良好!我不知道是什么导致了这个错误

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


您需要使用的不是
数据集,因此您的代码应该如下所示:

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

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

下面是我之前在这个论坛上发布的另一个问题的例子。您可以看到使用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();
        }
    }
}
以及存储库类:

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();
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
命名空间ToPagedList
{
公共类存储库
{
公共静态列表GetCourse1(字符串school=null,字符串code=null,字符串title=null,int page=0,int count=15)
{
var courses=新的DocumentModelEntities();
返回courses.Where(course=>string.IsNullOrEmpty(代码)| | course.CourseCode.Contains(代码))
.Where(course=>String.IsNullOrEmpty(title)| | course.title.Contains(title))
.Where(w=>String.IsNullOrEmpty(school)| | w.school==school)
//从这里,使用where子句从DB读取表
.选择(s=>新文档模型
{
Code=Code.Trim(),
Title=s.Title
})
.OrderBy(o=>o.Code)
.跳过(第*页计数)
.记(数)
.ToList();
}
公共静态列表GetCourse2(字符串school=null,字符串code=null,字符串title=null,int page=0,int count=15)
{
var courses=新的DocumentModelEntities();
返回courses.Where(course=>string.IsNullOrEmpty(代码)| | course.CourseCode.Contains(代码))
.Where(course=>String.IsNullOrEmpty(title)| | course.title.Contains(title))
.Where(w=>String.IsNullOrEmpty(school)| | w.school==school)
.OrderBy(course=>course.CourseCode)
.跳过(第*页计数)
.记(数)
//从这里,使用where子句、order by、skip和take从数据库中读取表
.选择(s=>新文档模型
{
Code=Code.Trim(),
Title=s.Title
})
.ToList();
}
}
}

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