Entlib5.0之資料查詢

來源:互聯網
上載者:User

        Entlib5.0早就出來了,在這個版本中提供了一些很好用的特性,今天小試一下,用用SprocAccessor和SqlStringAccessor這兩個類,這兩個類能夠將返回的DataSet, DataTable樣式的資料集轉換為實體資料的形式。

1.原始的查詢方式。

            Database db = DatabaseFactory.CreateDatabase();

            DbConnection connection = db.CreateConnection();
            DbCommand cmd = connection.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "select * from person";
            DataSet ds = db.ExecuteDataSet(cmd);

說明:關於資料連線的配置,請參考說明文檔,項目地址:http://entlib.codeplex.com/

 

2.採用預設的映射。這種映射資料庫列和實體資料的屬性是一一對應的。

資料庫中的列

 

實體類型:Person

    public class Person
    {
        public int PersonID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public DateTime? HireDate { get; set; }
        public DateTime? EnrollmentDate { get; set; }
        public override string ToString()
        {
            return string.Format(@"PersonID:{0},Name:{1}-{2}", PersonID, FirstName, LastName);
        }
    }

接下來看看我們如何查詢

            string sql1 = "select * from person";//查詢全部資料
            DataAccessor<Person> accessor = db.CreateSqlStringAccessor<Person>(sql1);
            List<Person> persons = accessor.Execute().ToList<Person>();
            persons.ForEach(p =>
            {
                Console.WriteLine(p.ToString());
            });

 

3.自訂映射。

   單行資料的映射,考慮到實際項目的情況,我們前段展示的資料形式(ViewModel)可能和原始的Model有些不一樣,這裡我們重新定義個實體類型,可能和資料庫列不存在一一對應的關係

/// <summary>
    /// 資料轉送對象
    /// </summary>
    public class PersonCourseGradeDTO
    {
        public string PersonName { get; set; }
        public string CourseName { get; set; }
        public double Grade { get; set; }
        public override string ToString()
        {
            return string.Format(@"PersonName:{0},CourseName:{1},Grade:{2}", PersonName, CourseName, Grade);
        }
    }

這個時候我們就需要自訂一個RowMapper了

    public class PersonRowMapper : IRowMapper<PersonCourseGradeDTO>
    {
        public PersonCourseGradeDTO MapRow(IDataRecord row)
        {
            PersonCourseGradeDTO dto = new PersonCourseGradeDTO();
            int col = row.GetOrdinal("FirstName");
            string FirstName = row.GetValue(col) == DBNull.Value ? "" : row.GetValue(col).ToString();
            col = row.GetOrdinal("LastName");
            string LastName = row.GetValue(col) == DBNull.Value ? "" : row.GetValue(col).ToString();
            col = row.GetOrdinal("Title");
            string Title = row.GetValue(col) == DBNull.Value ? "" : row.GetValue(col).ToString();
            col = row.GetOrdinal("Grade");
            double Grade = row.GetValue(col) == DBNull.Value ? 0 : Convert.ToDouble(row.GetValue(col));

            dto.PersonName = FirstName + "-" + LastName;
            dto.CourseName = Title;
            dto.Grade = Grade;
            return dto;
        }
    }

 

如何調用?

            IRowMapper<PersonCourseGradeDTO> rowMapper = new PersonRowMapper();
            DataAccessor<PersonCourseGradeDTO> PersonCourseGradeDTOAccessor = db.CreateSqlStringAccessor<PersonCourseGradeDTO>(sql3, rowMapper);
            List<PersonCourseGradeDTO> PersonCourseGradeDTOs = PersonCourseGradeDTOAccessor.Execute().ToList<PersonCourseGradeDTO>();
            PersonCourseGradeDTOs.ForEach(p =>
            {
                Console.WriteLine(p.ToString());
            });

多行資料的映射

    public class PersonRowsetMapper : IResultSetMapper<PersonCourseGradeDTO>
    {
        public IEnumerable<PersonCourseGradeDTO> MapSet(IDataReader reader)
        {
            while (reader.Read())
            {
                PersonCourseGradeDTO dto = new PersonCourseGradeDTO();
                int col = reader.GetOrdinal("FirstName");
                string FirstName = reader.GetValue(col) == DBNull.Value ? "" : reader.GetValue(col).ToString();
                col = reader.GetOrdinal("LastName");
                string LastName = reader.GetValue(col) == DBNull.Value ? "" : reader.GetValue(col).ToString();
                col = reader.GetOrdinal("Title");
                string Title = reader.GetValue(col) == DBNull.Value ? "" : reader.GetValue(col).ToString();
                col = reader.GetOrdinal("Grade");
                double Grade = reader.GetValue(col) == DBNull.Value ? 0 : Convert.ToDouble(reader.GetValue(col));

                dto.PersonName = FirstName + "-" + LastName;
                dto.CourseName = Title;
                dto.Grade = Grade;

                yield return dto;
            }
        }
    }

如何查詢?

           IResultSetMapper<PersonCourseGradeDTO> rowMapper2 = new PersonRowsetMapper();
            DataAccessor<PersonCourseGradeDTO> PersonCourseGradeDTOAccessor2 = db.CreateSqlStringAccessor<PersonCourseGradeDTO>(sql3, rowMapper2);
            List<PersonCourseGradeDTO> PersonCourseGradeDTOs2 = PersonCourseGradeDTOAccessor2.Execute().ToList<PersonCourseGradeDTO>();
            PersonCourseGradeDTOs2.ForEach(p =>
            {
                Console.WriteLine(p.ToString());
            });

 

入門文章,給初次接觸企業庫的朋友!

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.