日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > asp.net >内容正文

asp.net

.NET 常用ORM之SubSonic

發布時間:2023/12/31 asp.net 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 .NET 常用ORM之SubSonic 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、SubSonic簡單介紹

SubSonic是一個類似Rails的開源.NET項目。你可以把它看作是一把瑞士軍刀,它可以用來構建Website和通過ORM方式來訪問數據。Rob Conery和Eric Kemp是推動SubSonic的主要開發人員,與項目良好的發展有著密切的關系。是一個優秀的、開源的ORM映射框架。

另外官方有提供符合自身需要的代碼生成器sonic.exe,但是筆者在SubSonic并未下載到類代碼生成器,而是按照SubSonic的映射規則,在之前的用過的SubSonic的類上面做的修改,為下文的demo所使用,如果哪位朋友有SubSonic代碼生成器連接,歡迎共享一下給大家。

?

?二、SubSonic使用步驟

1、新增SubSonic配置文件并引入SubSonic.dll

配置文件并不多,有三處分別加入到web.config

<configSections> <section name="SubSonicService" type="SubSonic.SubSonicSection, SubSonic" allowDefinition="MachineToApplication" restartOnExternalChanges="true" requirePermission="false"/></configSections>

?

<connectionStrings><add name ="SubSonicConn" connectionString="Data Source=.;Initial Catalog=Test;Integrated Security=true;uid=sa;password=XXXXXX;"/></connectionStrings>

  

<SubSonicService defaultProvider="SubSonicConn" enableTrace="false" templateDirectory=""><providers><clear/><add name="SubSonicConn" type="SubSonic.SqlDataProvider, SubSonic"connectionStringName="SubSonicConn" generatedNamespace="SubSonicConn" removeUnderscores="false" /></providers></SubSonicService>

  配置文件就這樣,注意數據連接串的name值,包括后面項目中映射類文件的name值,一定要保持一致。

2、項目下新建Generated文件夾,保存SubSonic所需的類映射文件

其中Rolexxx相關為Role表的使用類,AllStructs.cs為主要的控制器文件,StoredProcedures.cs為存儲過程相關的類。具體類代碼如下:

using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace ORMSubSonic.Generated {#region Tables Structpublic partial struct Tables{public static readonly string Boy = @"boy";}#endregion#region Schemaspublic partial class Schemas {public static TableSchema.Table Boy{get { return DataService.GetSchema("boy", "SubSonicConn"); }}}#endregion#region View Structpublic partial struct Views {}#endregion#region Query Factoriespublic static partial class DB{public static DataProvider _provider = DataService.Providers["SubSonicConn"];static ISubSonicRepository _repository;public static ISubSonicRepository Repository {get {if (_repository == null)return new SubSonicRepository(_provider);return _repository; }set { _repository = value; }}public static Select SelectAllColumnsFrom<T>() where T : RecordBase<T>, new(){return Repository.SelectAllColumnsFrom<T>();}public static Select Select(){return Repository.Select();}public static Select Select(params string[] columns){return Repository.Select(columns);}public static Select Select(params Aggregate[] aggregates){return Repository.Select(aggregates);}public static Update Update<T>() where T : RecordBase<T>, new(){return Repository.Update<T>();}public static Insert Insert(){return Repository.Insert();}public static Delete Delete(){return Repository.Delete();}public static InlineQuery Query(){return Repository.Query();}}#endregion} #region Databases public partial struct Databases {public static readonly string SubSonicConn = @"SubSonicConn";} #endregion View Code

?

using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace ORMSubSonic.Generated {/// <summary>/// Strongly-typed collection for the Role class./// </summary> [Serializable]public partial class RoleCollection : ActiveList<Role, RoleCollection>{public RoleCollection() { }/// <summary>/// Filters an existing collection based on the set criteria. This is an in-memory filter/// Thanks to developingchris for this!/// </summary>/// <returns>RoleCollection</returns>public RoleCollection Filter(){for (int i = this.Count - 1; i > -1; i--){Role o = this[i];foreach (SubSonic.Where w in this.wheres){bool remove = false;System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);if (pi.CanRead){object val = pi.GetValue(o, null);switch (w.Comparison){case SubSonic.Comparison.Equals:if (!val.Equals(w.ParameterValue)){remove = true;}break;}}if (remove){this.Remove(o);break;}}}return this;}}/// <summary>/// This is an ActiveRecord class which wraps the Role table./// </summary> [Serializable]public partial class Role : ActiveRecord<Role>, IActiveRecord{#region .ctors and Default Settingspublic Role(){SetSQLProps();InitSetDefaults();MarkNew();}private void InitSetDefaults() { SetDefaults(); }public Role(bool useDatabaseDefaults){SetSQLProps();if (useDatabaseDefaults)ForceDefaults();MarkNew();}public Role(object keyID){SetSQLProps();InitSetDefaults();LoadByKey(keyID);}public Role(string columnName, object columnValue){SetSQLProps();InitSetDefaults();LoadByParam(columnName, columnValue);}protected static void SetSQLProps() { GetTableSchema(); }#endregion#region Schema and Query Accessorpublic static Query CreateQuery() { return new Query(Schema); }public static TableSchema.Table Schema{get{if (BaseSchema == null)SetSQLProps();return BaseSchema;}}private static void GetTableSchema(){if (!IsSchemaInitialized){//Schema declarationTableSchema.Table schema = new TableSchema.Table("Role", TableType.Table, DataService.GetInstance("SubSonicConn"));schema.Columns = new TableSchema.TableColumnCollection();schema.SchemaName = @"dbo";//columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema);colvarId.ColumnName = "id";colvarId.DataType = DbType.Int32;colvarId.MaxLength = 0;colvarId.AutoIncrement = true;colvarId.IsNullable = false;colvarId.IsPrimaryKey = true;colvarId.IsForeignKey = false;colvarId.IsReadOnly = false;colvarId.DefaultSetting = @"";colvarId.ForeignKeyTableName = "";schema.Columns.Add(colvarId);TableSchema.TableColumn colvarUid = new TableSchema.TableColumn(schema);colvarUid.ColumnName = "uid";colvarUid.DataType = DbType.Int32;colvarUid.MaxLength = 0;colvarUid.AutoIncrement = false;colvarUid.IsNullable = true;colvarUid.IsPrimaryKey = false;colvarUid.IsForeignKey = false;colvarUid.IsReadOnly = false;colvarUid.DefaultSetting = @"";colvarUid.ForeignKeyTableName = "";schema.Columns.Add(colvarUid);TableSchema.TableColumn colvarRoleName = new TableSchema.TableColumn(schema);colvarRoleName.ColumnName = "rolename";colvarRoleName.DataType = DbType.AnsiString;colvarRoleName.MaxLength = 250;colvarRoleName.AutoIncrement = false;colvarRoleName.IsNullable = true;colvarRoleName.IsPrimaryKey = false;colvarRoleName.IsForeignKey = false;colvarRoleName.IsReadOnly = false;colvarRoleName.DefaultSetting = @"";colvarRoleName.ForeignKeyTableName = "";schema.Columns.Add(colvarRoleName);TableSchema.TableColumn colvarRemark = new TableSchema.TableColumn(schema);colvarRemark.ColumnName = "remark";colvarRemark.DataType = DbType.AnsiString;colvarRemark.MaxLength = 50;colvarRemark.AutoIncrement = false;colvarRemark.IsNullable = true;colvarRemark.IsPrimaryKey = false;colvarRemark.IsForeignKey = false;colvarRemark.IsReadOnly = false;colvarRemark.DefaultSetting = @"";colvarRemark.ForeignKeyTableName = "";schema.Columns.Add(colvarRemark);BaseSchema = schema;//add this schema to the provider//so we can query it laterDataService.Providers["SubSonicConn"].AddSchema("Role", schema);}}#endregion#region Props[XmlAttribute("Id")][Bindable(true)]public int Id{get { return GetColumnValue<int>(Columns.Id); }set { SetColumnValue(Columns.Id, value); }}[XmlAttribute("Uid")][Bindable(true)]public int? Uid{get { return GetColumnValue<int?>(Columns.Uid); }set { SetColumnValue(Columns.Uid, value); }}[XmlAttribute("RoleName")][Bindable(true)]public string RoleName{get { return GetColumnValue<string>(Columns.RoleName); }set { SetColumnValue(Columns.RoleName, value); }}[XmlAttribute("Remark")][Bindable(true)]public string Remark{get { return GetColumnValue<string>(Columns.Remark); }set { SetColumnValue(Columns.Remark, value); }}#endregion//no foreign key tables defined (0)//no ManyToMany tables defined (0)#region ObjectDataSource support/// <summary>/// Inserts a record, can be used with the Object Data Source/// </summary>public static void Insert(int? varUid, string varRoleName, string varRemark){Role item = new Role();item.Uid = varUid;item.RoleName = varRoleName;item.Remark = varRemark;if (System.Web.HttpContext.Current != null)item.Save(System.Web.HttpContext.Current.User.Identity.Name);elseitem.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);}/// <summary>/// Updates a record, can be used with the Object Data Source/// </summary>public static void Update(int varId, int? varUid, string varRoleName, string varRemark){Role item = new Role();item.Id = varId;item.Uid = varUid;item.RoleName = varRoleName;item.Remark = varRemark;item.IsNew = false;if (System.Web.HttpContext.Current != null)item.Save(System.Web.HttpContext.Current.User.Identity.Name);elseitem.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);}#endregion#region Typed Columnspublic static TableSchema.TableColumn IdColumn{get { return Schema.Columns[0]; }}public static TableSchema.TableColumn UidColumn{get { return Schema.Columns[1]; }}public static TableSchema.TableColumn RoleNameColumn{get { return Schema.Columns[2]; }}public static TableSchema.TableColumn RemarkColumn{get { return Schema.Columns[3]; }}#endregion#region Columns Structpublic struct Columns{public static string Id = @"id";public static string Uid = @"uid";public static string RoleName = @"rolename";public static string Remark = @"remark";}#endregion#region Update PK Collections#endregion#region Deep Save#endregion} } View Code

?

using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace ORMSubSonic.Generated {/// <summary>/// Controller class for Role/// </summary> [System.ComponentModel.DataObject]public partial class RoleController{// Preload our schema..Role thisSchemaLoad = new Role();private string userName = String.Empty;protected string UserName{get{if (userName.Length == 0) {if (System.Web.HttpContext.Current != null){userName=System.Web.HttpContext.Current.User.Identity.Name;}else{userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;}}return userName;}}[DataObjectMethod(DataObjectMethodType.Select, true)]public RoleCollection FetchAll(){RoleCollection coll = new RoleCollection();Query qry = new Query(Role.Schema);coll.LoadAndCloseReader(qry.ExecuteReader());return coll;}[DataObjectMethod(DataObjectMethodType.Select, false)]public RoleCollection FetchByID(object Id){RoleCollection coll = new RoleCollection().Where("id", Id).Load();return coll;}[DataObjectMethod(DataObjectMethodType.Select, false)]public RoleCollection FetchByQuery(Query qry){RoleCollection coll = new RoleCollection();coll.LoadAndCloseReader(qry.ExecuteReader()); return coll;}[DataObjectMethod(DataObjectMethodType.Delete, true)]public bool Delete(object Id){return (Role.Delete(Id) == 1);}[DataObjectMethod(DataObjectMethodType.Delete, false)]public bool Destroy(object Id){return (Role.Destroy(Id) == 1);}/// <summary>/// Inserts a record, can be used with the Object Data Source/// </summary>[DataObjectMethod(DataObjectMethodType.Insert, true)]public void Insert(int? Uid,string RoleName,string Remark){Role item = new Role();item.Uid = Uid;item.RoleName = RoleName;item.Remark = Remark;item.Save(UserName);}/// <summary>/// Updates a record, can be used with the Object Data Source/// </summary>[DataObjectMethod(DataObjectMethodType.Update, true)]public void Update(int Id, int? Uid, string RoleName, string Remark){Role item = new Role();item.MarkOld();item.IsLoaded = true;item.Id = Id;item.Uid = Uid;item.RoleName = RoleName;item.Remark = Remark;item.Save(UserName);}} } View Code

?

using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace ORMSubSonic.Generated {public partial class SPs{}} View Code

?

3、實際使用

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SubSonic; using ORMSubSonic.Generated; using System.Data;namespace ORMSubSonic.Controllers {public class HomeController : Controller{//// GET: /Home/public ActionResult Index(){//1.增加Generated.Role modRole = new Generated.Role();modRole.Uid = 6;modRole.RoleName = "Subsonic操作手";modRole.Remark = "Subsonic操作手備注信息";modRole.Save();//2.刪除int result = DB.Delete().From(Role.Schema).Where(Role.Columns.Id).IsEqualTo("6").Execute();//3.修改int result2 = new Update(Role.Schema).Set(Role.Columns.RoleName).EqualTo("Subsonic操作手(修改)").Where(Role.Columns.Id).IsEqualTo("5").Execute();////4.查詢//DataTable dt= DB.Select().From(Role.Schema).ExecuteDataSet().Tables[0];DataTable dt = new Select().From(Role.Schema).ExecuteDataSet().Tables[0];////5.分頁查詢DataTable dt2 = new Select().From(Role.Schema).Paged(2,2,Role.Columns.Id).OrderAsc(Role.Columns.Id).ExecuteDataSet().Tables[0];return View();}} } View Code

?

4、SubSonic語法

SubSonic語法有點特別,用過SubSonic的人都比較喜歡SubSonic的語法,因人而異。在這里筆者就簡單的介紹下SubSonic常用的方法和關鍵字

4.1、常用方法

???ExecuteReader();???返回DataReader

?

???ExecuteScalar();???返回對象

?

???ExecuteScalar<string>();??返回泛型對象

?

???ExecuteSingle<Product>();?返回表實體對象

?

???ExecuteTypedList<Product>();??返回泛型表實休數據集

?

???ExecuteDataSet();??返回DataSet

?

???ExecuteJoinedDataSet<強數型數據集>();?返回關聯查詢?DataSet

?

???Execute();?返回執行后數據更新數目

?

4.2、常用關鍵字

???IsEqualTo(obj) //?等于?value

?

???IsBetweenAnd(obj1, obj2) // [字段1] BETWEEN?值1 AND?值2

?

???StartsWith??// LIEK '1%‘

?

???EndsWith????// LIEK '%1‘

?

???IsGreaterThan // [字段1] >?值1

?

???IsGreaterThanOrEqualToIsGreaterThan // [字段1] >=?值1

?

???IsLessThan???????????????????????// [字段1] <?值1

?

???IsLessThanOrEqualToIsLessThan????// [字段1] <=?值1

?

???WhereExpression / AndExpression??// Expression?表示括號

eg:

.Where("1").IsGreaterThan(1)
???????.And("2").IsGreaterThanOrEqualTo(2)
???????.AndExpression("3").IsLessThan(3)
???????.AndExpression("4").IsLessThanOrEqualTo(4).And("5").StartsWith("5")
???????.AndExpression("6").EndsWith("6")
???????.ExecuteSingle<Product>();

實際在SQL中執行語句則是:

where 1>1 and 2>=2 and (3<3) and (4<=4 and 5 like '5%') ?and (6 like '%6')

?

4.3、多表查詢

eg:查詢Product表中產品關聯的種類名稱,并且CategoryID大于4的記錄

?

DataSet?ds =?new?Select(Product.ProductNameColumn,?Category.CategoryIDColumn,Category.CategoryNameColumn)

?

????????????????.From<Product>()

?

????????????????.InnerJoin(Category.CategoryIDColumn,?Product.CategoryIDColumn)

?

????????????????.Where(Category.CategoryIDColumn) .IsGreaterThan(4)

?

????????????????.ExecuteDataSet().Table[0];

?

Select中的列則是在在DataGridView顯示的列ProductName,CategoryID,CategoryName

?

4.4、分頁查詢

在標題三代碼使用中已經使用到,在這里就不舉例說明,具體語法就是:

SqlQuery?Paged(int?currentPage,?int?pageSize);

?

SqlQuery?Paged(int?currentPage,?int?pageSize,?string?idColumn);

?

轉載于:https://www.cnblogs.com/become/p/8884299.html

總結

以上是生活随笔為你收集整理的.NET 常用ORM之SubSonic的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。