软件环境:

  • Win7 x64 SP1
  • SQL Server 2008r2
  • Visual Studio 2017 Professional

目标:取出示例数据库 ReportServer 的表 Roles 中的所有记录并显示。

步骤:

一、添加软件包

使用NuGet添加以下软件包:

ServiceStack

ServiceStack.OrmLite

 

二、定义表类

根据表Roles来定义对应的C#类:

    [Serializable]
    [Alias("Roles")]
    public class Role
    {
        public string RoleID { get; set; }
        public string RoleName { get; set; }
        public string Description { get; set; }
        public string TaskMask { get; set; }
        public int RoleFlags { get; set; }
    }

 

三、获取表数据并输出

            var dbFactory = new OrmLiteConnectionFactory("Server=(local);Database=ReportServer;Trusted_Connection=True;", SqlServerDialect.Provider);
            using(var db = dbFactory.Open())
            {
                var roles = db.Select<Role>();
                "Roles: {0}".Print(roles.Dump());
            }

 

完整的代码如下:

// RolesDemo.cs

using
System; using ServiceStack.Text; // for string.Print() using ServiceStack.OrmLite; using ServiceStack.DataAnnotations; // for [Alias()] namespace ConsoleApp1 { [Serializable] [Alias("Roles")] public class Role { public string RoleID { get; set; } public string RoleName { get; set; } public string Description { get; set; } public string TaskMask { get; set; } public int RoleFlags { get; set; } } class RolesDemo { public static void Run() { var dbFactory = new OrmLiteConnectionFactory("Server=(local);Database=ReportServer;Trusted_Connection=True;", SqlServerDialect.Provider); using(var db = dbFactory.Open()) { var roles = db.Select<Role>(); "Roles: {0}".Print(roles.Dump()); } } } }

 


// Program.cs
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            RolesDemo.Run();
        }
    }
}