軟體環境: Win7 x64 SP1 SQL Server 2008r2 Visual Studio 2017 Professional 目標:取出示例資料庫 ReportServer 的表 Roles 中的所有記錄並顯示。 步驟: 一、添加軟體包 使用NuGet添加以下軟體包: ServiceSt ...
軟體環境:
- 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(); } } }