如何将datareader或数据表反序列化为c#类

时间:2013-02-28 12:06:07

标签: c#

我已经从db表中填充了数据阅读器,我有类似

的类
public class CandidateApplication
{
                public string EmailID { get; set; }
                public string Name { get; set; }
                public string PhoneNo { get; set; }
                public string CurrentLocation { get; set; }
                public string PreferredWorkLocation { get; set; }
                public int RoleApplingFor { get; set; }
                public string CurrentJobTitle { get; set; }
                public int EducationLevel { get; set; }
                public decimal SalaryExpected { get; set; }
                public string AvailableTime { get; set; }
                public int AdvertID { get; set; }
                public bool SignForAlert { get; set; }
                public string CVInText { get; set; }
                public string CVFileName { get; set; }
                public bool IsDownloaded { get; set; }
                public string specialization { get; set; }
                public bool isallocated { get; set; }
                public int id { get; set; }
                public string AdvertAdditionalInfo { get; set; }
}

我可以在循环中填充上面的类。我们可以迭代数据阅读器并填充类但我想知道是否有任何捷径方式从数据阅读器填充类。

如果可以从数据读取器到类进行数据反序列化,那么还要告诉我,如果类中没有数据库中没有的字段,那么如何处理这种情况。

2 个答案:

答案 0 :(得分:2)

虽然不是您问题的答案,但我建议您考虑使用SqlDataAdapter代替数据阅读器的以下解决方法:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Xml.Serialization;

class Program
{
    static void Main(string[] args)
    {

        var cs = "YourConnectionString";
        var xml = "";
        using (var con = new SqlConnection(cs))
        using (var c = new SqlCommand("SELECT * FROM CandidateApplication", con))
        {
            con.Open();
            using (var adapter = new SqlDataAdapter(c))
            {
                var ds = new DataSet("CandidateApplications");
                ds.Tables.Add("CandidateApplication");
                adapter.Fill(ds, ds.Tables[0].TableName);
                xml = ds.GetXml();
            }
        }

        // We need to specify the root element
        var rootAttribute = new XmlRootAttribute();

        // The class to use as the XML root element (should match the name of 
        // the DataTable in the DataSet above)
        rootAttribute.ElementName = "CandidateApplications";

        // Initializes a new instance of the XmlSerializer class that can 
        // serialize objects of the specified type into XML documents, and 
        // deserialize an XML document into object of the specified type. 
        // It also specifies the class to use as the XML root element.
        // I chose List<CandidateApplication> as the type because I find it
        // easier to work with (but CandidateApplication[] will also work)
        var xs = new XmlSerializer(typeof(List<CandidateApplication>), rootAttribute);

        // Deserialize the XML document contained by the specified TextReader, 
        // in our case, a StringReader instance constructed with xml as a parameter.
        List<CandidateApplication> results = xs.Deserialize(new StringReader(xml));
    }
}

对于检索到的数据中缺少的那些属性,您可以声明具有默认值的私有字段:

string _advertAdditionalInfo = "default";
public string AdvertAdditionalInfo
{
    get
    {
        return _advertAdditionalInfo;
    }
    set
    {
        _advertAdditionalInfo = value;
    }
}

如果您希望强制检索到的数据不会填写特定属性,请使用:

[XmlIgnoreAttribute]
public string AdvertAdditionalInfo { get; set; }

答案 1 :(得分:1)

您不需要使用数据读取器,只需将数据填充到DataTable中,然后使用以下方法创建CandidateApplication类的列表。

电话: -

List<CandidateApplication> CandidateList = GetCandidateInformation();

生成列表的方法: -

public List<CandidateApplication> GetCandidateInformation()
        {
            DataTable dt = new DataTable();

            using (OleDbConnection con = new OleDbConnection(ConfigurationManager.AppSettings["con"]))
            {
                using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [TableName]", con))
                {
                    var adapter = new OleDbDataAdapter();
                    adapter.SelectCommand = cmd;

                    con.Open();
                    adapter.Fill(dt);

                    var CandApp = (from row in dt.AsEnumerable()

                    select new CandidateApplication
                    {

                    EmailID = row.Field<string>("EmailID"),
                    Name  = row.Field<string>("Name"),
                    PhoneNo = row.Field<string>("PhoneNo"),
                    CurrentLocation = row.Field<string>("CurrentLocation"),
                    PreferredWorkLocation = row.Field<string>("PreferredWorkLocation"),
                    RoleApplingFor = row.Field<int>("RoleApplingFor"),
                    CurrentJobTitle = row.Field<string>("CurrentJobTitle"),
                    EducationLevel = row.Field<int>("EducationLevel "),
                    SalaryExpected = row.Field<decimal>("SalaryExpected"),
                    AvailableTime = row.Field<string>("AvailableTime"),
                    AdvertID = row.Field<int>("AdvertID"),
                    SignForAlert = row.Field<bool>("SignForAlert"),
                    CVInText = row.Field<string>("CVInText"),
                    CVFileName = row.Field<string>("CVFileName"),
                    IsDownloaded = row.Field<bool>("IsDownloaded"),
                    Specialization = row.Field<string>("Specialization"),
                    Isallocated = row.Field<bool>("Isallocated"),
                    Id = row.Field<int>("Id"),
                    AdvertAdditionalInfo = row.Field<string>("AdvertAdditionalInfo")


                    }).ToList();

                    return CandApp;
                }
            }
        }