采用CSLA.net 2.1.4.0版本的书写方式:
1 using System; 2 using System.ComponentModel; 3 using Csla.Validation; 4 using System.Data.OleDb; 5 using DBDemo.DbUtility; 6 using System.Data; 7 8 namespace DBDemo.MVC.Model 9 { 10 class Student:Csla.BusinessBase<Student> 11 { 12 #region Business Properties and Methods 13 14 private int _id = 0; 15 [DisplayNameAttribute("ID"), DescriptionAttribute("ID")] 16 public int ID 17 { 18 get 19 { 20 CanReadProperty("ID", true); 21 return _id; 22 } 23 } 24 25 private string _name = "<空>"; 26 [DisplayNameAttribute("姓名"), DescriptionAttribute("姓名")] 27 public string Name 28 { 29 get 30 { 31 CanReadProperty("Name", true); 32 return _name; 33 } 34 set 35 { 36 CanWriteProperty("Name", true); 37 if (value == null) value = string.Empty; 38 if (_name != value) 39 { 40 _name = value.Trim(); 41 PropertyHasChanged("Name"); 42 } 43 } 44 } 45 46 private int _age = 1; 47 [DisplayNameAttribute("年龄"), DescriptionAttribute("年龄")] 48 public int Age 49 { 50 get 51 { 52 CanReadProperty("Age", true); 53 return _age; 54 } 55 set 56 { 57 CanWriteProperty("Age", true); 58 if (_age != value) 59 { 60 _age = value; 61 PropertyHasChanged("Age"); 62 } 63 } 64 } 65 66 67 private DateTime _birth = DateTime.Now; 68 [DisplayNameAttribute("生日"), DescriptionAttribute("生日")] 69 public DateTime Birth 70 { 71 get 72 { 73 CanReadProperty("Birth", true); 74 return _birth; 75 } 76 set 77 { 78 CanWriteProperty("Birth", true); 79 if (_birth != value) 80 { 81 _birth = value; 82 PropertyHasChanged("Birth"); 83 } 84 } 85 } 86 87 protected override object GetIdValue() 88 { 89 return _id; 90 } 91 92 #endregion //Business Properties and Methods 93 94 #region Validation Rules 95 private void AddCustomRules() 96 { 97 //add custom/non-generated rules here... 98 } 99 100 private void AddCommonRules() 101 { 102 // 103 // Name 104 // 105 ValidationRules.AddRule(CommonRules.StringRequired, "Name"); 106 ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Name", 8)); 107 ValidationRules.AddRule(CommonRules.IntegerMinValue, new CommonRules.IntegerMinValueRuleArgs("Age", 0)); 108 ValidationRules.AddRule(CommonRules.IntegerMaxValue, new CommonRules.IntegerMaxValueRuleArgs("Age", 120)); 109 } 110 111 protected override void AddBusinessRules() 112 { 113 AddCommonRules(); 114 AddCustomRules(); 115 } 116 #endregion //Validation Rules 117 118 #region Authorization Rules 119 protected override void AddAuthorizationRules() 120 { 121 //TODO: Define authorization rules in HPrecision 122 //AuthorizationRules.AllowRead("Code", "HPrecisionReadGroup"); 123 124 //AuthorizationRules.AllowWrite("Name", "HPrecisionWriteGroup"); 125 126 } 127 128 #endregion //Authorization Rules 129 130 #region Factory Methods 131 public static Student New() 132 { 133 return new Student(); 134 } 135 136 internal static Student Get(OleDbDataReader row) 137 { 138 Student obj = new Student(); 139 obj.Fetch( row ); 140 return obj; 141 } 142 143 private Student() 144 { 145 MarkAsChild(); 146 } 147 148 #endregion //Factory Methods 149 150 #region Data Access - Fetch 151 private void Fetch(OleDbDataReader row) 152 { 153 object objv = null; 154 objv = row["ID"]; 155 _id = Convert.IsDBNull(objv) ? 0 : Convert.ToInt16(objv); 156 157 objv = row["StudentName"]; 158 _name = Convert.IsDBNull(objv) ? string.Empty : Convert.ToString(objv); 159 objv = row["Age"]; 160 _age = Convert.IsDBNull(objv) ? 0 : Convert.ToInt32(objv); 161 162 objv = row["BirthDay"]; 163 _birth = Convert.IsDBNull(objv) ? DateTime.MinValue : Convert.ToDateTime(objv); 164 165 MarkOld(); 166 167 ValidationRules.CheckRules(); 168 } 169 #endregion //Data Access - Fetch 170 171 #region Data Access - Update,Insert,Delete 172 internal void Update() 173 { 174 if (!IsDirty) return; 175 if (this.IsDeleted)//删除的记录 176 { 177 //is deleted object, check if new 178 if (!this.IsNew) 179 { 180 string sqlDelete =string.Format( "delete from [Student] where ID={0} ",_id); 181 OleDbHelper.ExecuteNonQuery(OleDbHelper.connectionString,CommandType.Text,sqlDelete,null); 182 MarkNew(); 183 } 184 } 185 else 186 { 187 if (this.IsNew)//新添加的记录 188 { 189 string sqlInsert = string.Format("insert into [Student](StudentName,[Age],[BirthDay]) values(‘{0}‘,{1},‘{2}‘) ", _name,_age,_birth); 190 OleDbHelper.ExecuteNonQuery(OleDbHelper.connectionString, CommandType.Text, sqlInsert, null); 191 192 //_id =0; 193 //PropertyHasChanged("ID"); 194 } 195 else //修改的记录 196 { 197 198 string sqlUpdate = string.Format("update [Student] set StudentName=‘{0}‘,Age={1} where ID={2} ",_name,_age, _id); 199 OleDbHelper.ExecuteNonQuery(OleDbHelper.connectionString, CommandType.Text, sqlUpdate, null); 200 } 201 202 // mark the object as old (persisted) 203 MarkOld(); 204 } 205 } 206 private void AddParametersValues() 207 { 208 209 210 211 } 212 #endregion //Data Access 213 } 214 }
1 using System; 2 using Csla; 3 using DBDemo.DbUtility; 4 using System.Data.OleDb; 5 6 namespace DBDemo.MVC.Model 7 { 8 class StudentList:Csla.BusinessListBase<StudentList,Student> 9 { 10 protected override object AddNewCore() 11 { 12 Student item = Student.New(); 13 Add(item); 14 return item; 15 } 16 17 18 #region 支持bindingSource的Find方法 19 protected override bool SupportsSearchingCore 20 { 21 get 22 { 23 return true; 24 } 25 } 26 27 protected override int FindCore(System.ComponentModel.PropertyDescriptor prop, object key) 28 { 29 if (prop.Name == "Name") 30 { 31 for (int i = 0; i < Count; i++) 32 { 33 if (this[i].Name == (string)key ) return i; 34 } 35 } 36 else if (prop.Name == "Name") 37 { 38 for (int i = 0; i < Count; i++) 39 { 40 if (this[i].Name == (string)key ) return i; 41 } 42 } 43 return -1; 44 } 45 #endregion 46 47 #region Authorization Rules 48 49 public static bool CanGetObject() 50 { 51 //TODO: Define CanGetObject permission in HPrecisions 52 return true; 53 //if (Csla.ApplicationContext.User.IsInRole("HPrecisionsViewGroup")) 54 // return true; 55 //return false; 56 } 57 58 public static bool CanAddObject() 59 { 60 //TODO: Define CanAddObject permission in HPrecisions 61 return true; 62 //if (Csla.ApplicationContext.User.IsInRole("HPrecisionsAddGroup")) 63 // return true; 64 //return false; 65 } 66 67 public static bool CanEditObject() 68 { 69 //TODO: Define CanEditObject permission in HPrecisions 70 return true; 71 //if (Csla.ApplicationContext.User.IsInRole("HPrecisionsEditGroup")) 72 // return true; 73 //return false; 74 } 75 76 public static bool CanDeleteObject() 77 { 78 //TODO: Define CanDeleteObject permission in HPrecisions 79 return true; 80 //if (Csla.ApplicationContext.User.IsInRole("HPrecisionsDeleteGroup")) 81 // return true; 82 //return false; 83 } 84 #endregion //Authorization Rules 85 86 #region Factory Methods 87 private StudentList() 88 { 89 AllowNew = true; 90 AllowRemove = true; 91 AllowEdit = true; 92 } 93 94 public static StudentList New() 95 { 96 if (!CanAddObject()) 97 throw new System.Security.SecurityException("You can not add new Hole !"); 98 return new StudentList(); 99 } 100 101 public static StudentList Get() 102 { 103 if (!CanGetObject()) 104 throw new System.Security.SecurityException("You can not view new Hole !"); 105 return DataPortal.Fetch<StudentList>(new Criteria()); 106 } 107 #endregion //Factory Methods 108 109 #region Data Access 110 111 #region Filter Criteria 112 [Serializable()] 113 private class Criteria 114 { 115 } 116 #endregion //Filter Criteria 117 118 #region Data Access - Fetch 119 120 /// <summary> 121 /// 从Access获取表中所有数据 122 /// </summary> 123 /// <param name="cr">条件</param> 124 private void DataPortal_Fetch(Criteria cr) 125 { 126 RaiseListChangedEvents = false; 127 string sql = "select * from [Student]"; 128 OleDbDataReader dr = DbUtility.OleDbHelper.ExecuteReader(OleDbHelper.connectionString, sql); 129 if (dr != null) 130 { 131 if (dr.HasRows) 132 { 133 while (dr.Read()) 134 { 135 this.Add(Student.Get(dr)); 136 } 137 } 138 } 139 140 RaiseListChangedEvents = true; 141 } 142 143 protected override void DataPortal_Update() 144 { 145 RaiseListChangedEvents = false; 146 // loop through each deleted child object 147 foreach (Student deletedChild in DeletedList) 148 deletedChild.Update(); 149 DeletedList.Clear(); 150 151 // loop through each non-deleted child object 152 foreach (Student child in this) child.Update(); 153 154 RaiseListChangedEvents = true; 155 } 156 #endregion //Data Access - Update 157 #endregion //Data Access 158 } 159 }
采用CSLA.net 3.6版本的书写方式:
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using Csla; 5 6 namespace BLBTest 7 { 8 [Serializable] 9 public class DataEdit : BusinessBase<DataEdit> 10 { 11 int _data; 12 public int Data 13 { 14 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] 15 get 16 { 17 CanReadProperty(true); 18 return _data; 19 } 20 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] 21 set 22 { 23 CanWriteProperty(true); 24 if (!_data.Equals(value)) 25 { 26 _data = value; 27 PropertyHasChanged(); 28 } 29 } 30 } 31 32 string _name = string.Empty; 33 public string Name 34 { 35 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] 36 get 37 { 38 CanReadProperty(true); 39 return _name; 40 } 41 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] 42 set 43 { 44 CanWriteProperty(true); 45 if (value == null) value = string.Empty; 46 if (!_name.Equals(value)) 47 { 48 _name = value; 49 PropertyHasChanged(); 50 } 51 } 52 } 53 54 protected override void AddBusinessRules() 55 { 56 ValidationRules.AddRule( 57 Csla.Validation.CommonRules.MinValue<int>, 58 new Csla.Validation.CommonRules.MinValueRuleArgs<int>("Data", 10)); 59 60 ValidationRules.AddRule( 61 Csla.Validation.CommonRules.StringRequired, "Name"); 62 } 63 64 protected override object GetIdValue() 65 { 66 return _data; 67 } 68 69 public DataEdit() 70 { 71 MarkAsChild(); 72 } 73 74 public DataEdit(int id, string name) 75 : this() 76 { 77 _data = id; 78 _name = name; 79 } 80 81 public int CurrentEditLevel 82 { 83 get 84 { 85 return EditLevel; 86 } 87 } 88 89 public int CurrentEditLevelAdded 90 { 91 get 92 { 93 Csla.Core.IEditableBusinessObject ebo = (Csla.Core.IEditableBusinessObject)this; 94 return ebo.EditLevelAdded; 95 } 96 } 97 98 protected override void AcceptChangesComplete() 99 { 100 System.Diagnostics.Debug.WriteLine(string.Format("Acc: {0} ({1}, {2})", _data, CurrentEditLevel, CurrentEditLevelAdded)); 101 base.AcceptChangesComplete(); 102 } 103 104 protected override void UndoChangesComplete() 105 { 106 System.Diagnostics.Debug.WriteLine(string.Format("Und: {0} ({1}, {2})", _data, CurrentEditLevel, CurrentEditLevelAdded)); 107 base.UndoChangesComplete(); 108 } 109 110 protected override void CopyStateComplete() 111 { 112 System.Diagnostics.Debug.WriteLine(string.Format("Beg: {0} ({1}, {2})", _data, CurrentEditLevel, CurrentEditLevelAdded)); 113 base.CopyStateComplete(); 114 } 115 } 116 }
1 using System; 2 using System.Collections.Generic; 3 using System.Text; 4 using Csla; 5 6 namespace BLBTest 7 { 8 [Serializable] 9 public class DataList : BusinessListBase<DataList, DataEdit> 10 { 11 public DataList() 12 { 13 AllowEdit = true; 14 AllowNew = true; 15 AllowRemove = true; 16 } 17 18 protected override object AddNewCore() 19 { 20 DataEdit item = new DataEdit(); 21 Add(item); 22 return item; 23 } 24 } 25 }
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Text; 7 using System.Windows.Forms; 8 9 namespace BLBTest 10 { 11 public partial class Form1 : Form 12 { 13 public Form1() 14 { 15 InitializeComponent(); 16 } 17 18 private void Form1_Load(object sender, EventArgs e) 19 { 20 DataList list = new DataList(); 21 list.Add(new DataEdit(1, "Rocky")); 22 list.Add(new DataEdit(2, "Fred")); 23 list.Add(new DataEdit(3, "Mary")); 24 list.Add(new DataEdit(4, "George")); 25 list.BeginEdit(); 26 this.dataListBindingSource.DataSource = list; 27 this.dataListBindingSource.ListChanged += new ListChangedEventHandler(dataListBindingSource_ListChanged); 28 } 29 30 void dataListBindingSource_ListChanged(object sender, ListChangedEventArgs e) 31 { 32 System.Diagnostics.Debug.WriteLine( 33 string.Format("{0}: {1}, {2}",e.ListChangedType.ToString(), e.NewIndex, e.OldIndex)); 34 } 35 36 private void toolStripButton1_Click(object sender, EventArgs e) 37 { 38 DataEdit item = new DataEdit(100, "Abdul"); 39 ((DataList)this.dataListBindingSource.DataSource)[1] = item; 40 System.Diagnostics.Debug.WriteLine( 41 string.Format("{0}: {1}, {2}", item.Data, item.CurrentEditLevel, item.CurrentEditLevelAdded)); 42 } 43 44 private void toolStripButton2_Click(object sender, EventArgs e) 45 { 46 DataList list = (DataList)this.dataListBindingSource.DataSource; 47 this.dataListBindingSource.CancelEdit(); 48 list.CancelEdit(); 49 list.BeginEdit(); 50 } 51 52 private void cancelButton_Click(object sender, EventArgs e) 53 { 54 // get business object reference 55 DataList list = (DataList)this.dataListBindingSource.DataSource; 56 57 // cancel current row 58 this.dataListBindingSource.CancelEdit(); 59 60 // unbind the UI 61 UnbindBindingSource(this.dataListBindingSource); 62 63 // cancel the list and restart editing 64 list.CancelEdit(); 65 list.BeginEdit(); 66 67 // rebind the UI 68 this.dataListBindingSource.DataSource = list; 69 } 70 71 private void UnbindBindingSource(BindingSource source) 72 { 73 System.ComponentModel.IEditableObject current = 74 this.dataListBindingSource.Current as System.ComponentModel.IEditableObject; 75 this.dataListBindingSource.DataSource = null; 76 if (current != null) 77 current.EndEdit(); 78 } 79 } 80 }