CSLA.Net学习(2)

时间:2023-03-10 04:25:38
CSLA.Net学习(2)

采用CSLA.net 2.1.4.0版本的书写方式:

 using System;
using System.ComponentModel;
using Csla.Validation;
using System.Data.OleDb;
using DBDemo.DbUtility;
using System.Data; namespace DBDemo.MVC.Model
{
class Student:Csla.BusinessBase<Student>
{
#region Business Properties and Methods private int _id = ;
[DisplayNameAttribute("ID"), DescriptionAttribute("ID")]
public int ID
{
get
{
CanReadProperty("ID", true);
return _id;
}
} private string _name = "<空>";
[DisplayNameAttribute("姓名"), DescriptionAttribute("姓名")]
public string Name
{
get
{
CanReadProperty("Name", true);
return _name;
}
set
{
CanWriteProperty("Name", true);
if (value == null) value = string.Empty;
if (_name != value)
{
_name = value.Trim();
PropertyHasChanged("Name");
}
}
} private int _age = ;
[DisplayNameAttribute("年龄"), DescriptionAttribute("年龄")]
public int Age
{
get
{
CanReadProperty("Age", true);
return _age;
}
set
{
CanWriteProperty("Age", true);
if (_age != value)
{
_age = value;
PropertyHasChanged("Age");
}
}
} private DateTime _birth = DateTime.Now;
[DisplayNameAttribute("生日"), DescriptionAttribute("生日")]
public DateTime Birth
{
get
{
CanReadProperty("Birth", true);
return _birth;
}
set
{
CanWriteProperty("Birth", true);
if (_birth != value)
{
_birth = value;
PropertyHasChanged("Birth");
}
}
} protected override object GetIdValue()
{
return _id;
} #endregion //Business Properties and Methods #region Validation Rules
private void AddCustomRules()
{
//add custom/non-generated rules here...
} private void AddCommonRules()
{
//
// Name
//
ValidationRules.AddRule(CommonRules.StringRequired, "Name");
ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("Name", ));
ValidationRules.AddRule(CommonRules.IntegerMinValue, new CommonRules.IntegerMinValueRuleArgs("Age", ));
ValidationRules.AddRule(CommonRules.IntegerMaxValue, new CommonRules.IntegerMaxValueRuleArgs("Age", ));
} protected override void AddBusinessRules()
{
AddCommonRules();
AddCustomRules();
}
#endregion //Validation Rules #region Authorization Rules
protected override void AddAuthorizationRules()
{
//TODO: Define authorization rules in HPrecision
//AuthorizationRules.AllowRead("Code", "HPrecisionReadGroup"); //AuthorizationRules.AllowWrite("Name", "HPrecisionWriteGroup"); } #endregion //Authorization Rules #region Factory Methods
public static Student New()
{
return new Student();
} internal static Student Get(OleDbDataReader row)
{
Student obj = new Student();
obj.Fetch( row );
return obj;
} private Student()
{
MarkAsChild();
} #endregion //Factory Methods #region Data Access - Fetch
private void Fetch(OleDbDataReader row)
{
object objv = null;
objv = row["ID"];
_id = Convert.IsDBNull(objv) ? : Convert.ToInt16(objv); objv = row["StudentName"];
_name = Convert.IsDBNull(objv) ? string.Empty : Convert.ToString(objv);
objv = row["Age"];
_age = Convert.IsDBNull(objv) ? : Convert.ToInt32(objv); objv = row["BirthDay"];
_birth = Convert.IsDBNull(objv) ? DateTime.MinValue : Convert.ToDateTime(objv); MarkOld(); ValidationRules.CheckRules();
}
#endregion //Data Access - Fetch #region Data Access - Update,Insert,Delete
internal void Update()
{
if (!IsDirty) return;
if (this.IsDeleted)//删除的记录
{
//is deleted object, check if new
if (!this.IsNew)
{
string sqlDelete =string.Format( "delete from [Student] where ID={0} ",_id);
OleDbHelper.ExecuteNonQuery(OleDbHelper.connectionString,CommandType.Text,sqlDelete,null);
MarkNew();
}
}
else
{
if (this.IsNew)//新添加的记录
{
string sqlInsert = string.Format("insert into [Student](StudentName,[Age],[BirthDay]) values('{0}',{1},'{2}') ", _name,_age,_birth);
OleDbHelper.ExecuteNonQuery(OleDbHelper.connectionString, CommandType.Text, sqlInsert, null); //_id =0;
//PropertyHasChanged("ID");
}
else //修改的记录
{ string sqlUpdate = string.Format("update [Student] set StudentName='{0}',Age={1} where ID={2} ",_name,_age, _id);
OleDbHelper.ExecuteNonQuery(OleDbHelper.connectionString, CommandType.Text, sqlUpdate, null);
} // mark the object as old (persisted)
MarkOld();
}
}
private void AddParametersValues()
{ }
#endregion //Data Access
}
}

Student

 using System;
using Csla;
using DBDemo.DbUtility;
using System.Data.OleDb; namespace DBDemo.MVC.Model
{
class StudentList:Csla.BusinessListBase<StudentList,Student>
{
protected override object AddNewCore()
{
Student item = Student.New();
Add(item);
return item;
} #region 支持bindingSource的Find方法
protected override bool SupportsSearchingCore
{
get
{
return true;
}
} protected override int FindCore(System.ComponentModel.PropertyDescriptor prop, object key)
{
if (prop.Name == "Name")
{
for (int i = ; i < Count; i++)
{
if (this[i].Name == (string)key ) return i;
}
}
else if (prop.Name == "Name")
{
for (int i = ; i < Count; i++)
{
if (this[i].Name == (string)key ) return i;
}
}
return -;
}
#endregion #region Authorization Rules public static bool CanGetObject()
{
//TODO: Define CanGetObject permission in HPrecisions
return true;
//if (Csla.ApplicationContext.User.IsInRole("HPrecisionsViewGroup"))
// return true;
//return false;
} public static bool CanAddObject()
{
//TODO: Define CanAddObject permission in HPrecisions
return true;
//if (Csla.ApplicationContext.User.IsInRole("HPrecisionsAddGroup"))
// return true;
//return false;
} public static bool CanEditObject()
{
//TODO: Define CanEditObject permission in HPrecisions
return true;
//if (Csla.ApplicationContext.User.IsInRole("HPrecisionsEditGroup"))
// return true;
//return false;
} public static bool CanDeleteObject()
{
//TODO: Define CanDeleteObject permission in HPrecisions
return true;
//if (Csla.ApplicationContext.User.IsInRole("HPrecisionsDeleteGroup"))
// return true;
//return false;
}
#endregion //Authorization Rules #region Factory Methods
private StudentList()
{
AllowNew = true;
AllowRemove = true;
AllowEdit = true;
} public static StudentList New()
{
if (!CanAddObject())
throw new System.Security.SecurityException("You can not add new Hole !");
return new StudentList();
} public static StudentList Get()
{
if (!CanGetObject())
throw new System.Security.SecurityException("You can not view new Hole !");
return DataPortal.Fetch<StudentList>(new Criteria());
}
#endregion //Factory Methods #region Data Access #region Filter Criteria
[Serializable()]
private class Criteria
{
}
#endregion //Filter Criteria #region Data Access - Fetch /// <summary>
/// 从Access获取表中所有数据
/// </summary>
/// <param name="cr">条件</param>
private void DataPortal_Fetch(Criteria cr)
{
RaiseListChangedEvents = false;
string sql = "select * from [Student]";
OleDbDataReader dr = DbUtility.OleDbHelper.ExecuteReader(OleDbHelper.connectionString, sql);
if (dr != null)
{
if (dr.HasRows)
{
while (dr.Read())
{
this.Add(Student.Get(dr));
}
}
} RaiseListChangedEvents = true;
} protected override void DataPortal_Update()
{
RaiseListChangedEvents = false;
// loop through each deleted child object
foreach (Student deletedChild in DeletedList)
deletedChild.Update();
DeletedList.Clear(); // loop through each non-deleted child object
foreach (Student child in this) child.Update(); RaiseListChangedEvents = true;
}
#endregion //Data Access - Update
#endregion //Data Access
}
}

StudentList

采用CSLA.net 3.6版本的书写方式:

 using System;
using System.Collections.Generic;
using System.Text;
using Csla; namespace BLBTest
{
[Serializable]
public class DataEdit : BusinessBase<DataEdit>
{
int _data;
public int Data
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _data;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (!_data.Equals(value))
{
_data = value;
PropertyHasChanged();
}
}
} string _name = string.Empty;
public string Name
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _name;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (!_name.Equals(value))
{
_name = value;
PropertyHasChanged();
}
}
} protected override void AddBusinessRules()
{
ValidationRules.AddRule(
Csla.Validation.CommonRules.MinValue<int>,
new Csla.Validation.CommonRules.MinValueRuleArgs<int>("Data", )); ValidationRules.AddRule(
Csla.Validation.CommonRules.StringRequired, "Name");
} protected override object GetIdValue()
{
return _data;
} public DataEdit()
{
MarkAsChild();
} public DataEdit(int id, string name)
: this()
{
_data = id;
_name = name;
} public int CurrentEditLevel
{
get
{
return EditLevel;
}
} public int CurrentEditLevelAdded
{
get
{
Csla.Core.IEditableBusinessObject ebo = (Csla.Core.IEditableBusinessObject)this;
return ebo.EditLevelAdded;
}
} protected override void AcceptChangesComplete()
{
System.Diagnostics.Debug.WriteLine(string.Format("Acc: {0} ({1}, {2})", _data, CurrentEditLevel, CurrentEditLevelAdded));
base.AcceptChangesComplete();
} protected override void UndoChangesComplete()
{
System.Diagnostics.Debug.WriteLine(string.Format("Und: {0} ({1}, {2})", _data, CurrentEditLevel, CurrentEditLevelAdded));
base.UndoChangesComplete();
} protected override void CopyStateComplete()
{
System.Diagnostics.Debug.WriteLine(string.Format("Beg: {0} ({1}, {2})", _data, CurrentEditLevel, CurrentEditLevelAdded));
base.CopyStateComplete();
}
}
}

DataEdit

 using System;
using System.Collections.Generic;
using System.Text;
using Csla; namespace BLBTest
{
[Serializable]
public class DataList : BusinessListBase<DataList, DataEdit>
{
public DataList()
{
AllowEdit = true;
AllowNew = true;
AllowRemove = true;
} protected override object AddNewCore()
{
DataEdit item = new DataEdit();
Add(item);
return item;
}
}
}

DataList

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms; namespace BLBTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void Form1_Load(object sender, EventArgs e)
{
DataList list = new DataList();
list.Add(new DataEdit(, "Rocky"));
list.Add(new DataEdit(, "Fred"));
list.Add(new DataEdit(, "Mary"));
list.Add(new DataEdit(, "George"));
list.BeginEdit();
this.dataListBindingSource.DataSource = list;
this.dataListBindingSource.ListChanged += new ListChangedEventHandler(dataListBindingSource_ListChanged);
} void dataListBindingSource_ListChanged(object sender, ListChangedEventArgs e)
{
System.Diagnostics.Debug.WriteLine(
string.Format("{0}: {1}, {2}",e.ListChangedType.ToString(), e.NewIndex, e.OldIndex));
} private void toolStripButton1_Click(object sender, EventArgs e)
{
DataEdit item = new DataEdit(, "Abdul");
((DataList)this.dataListBindingSource.DataSource)[] = item;
System.Diagnostics.Debug.WriteLine(
string.Format("{0}: {1}, {2}", item.Data, item.CurrentEditLevel, item.CurrentEditLevelAdded));
} private void toolStripButton2_Click(object sender, EventArgs e)
{
DataList list = (DataList)this.dataListBindingSource.DataSource;
this.dataListBindingSource.CancelEdit();
list.CancelEdit();
list.BeginEdit();
} private void cancelButton_Click(object sender, EventArgs e)
{
// get business object reference
DataList list = (DataList)this.dataListBindingSource.DataSource; // cancel current row
this.dataListBindingSource.CancelEdit(); // unbind the UI
UnbindBindingSource(this.dataListBindingSource); // cancel the list and restart editing
list.CancelEdit();
list.BeginEdit(); // rebind the UI
this.dataListBindingSource.DataSource = list;
} private void UnbindBindingSource(BindingSource source)
{
System.ComponentModel.IEditableObject current =
this.dataListBindingSource.Current as System.ComponentModel.IEditableObject;
this.dataListBindingSource.DataSource = null;
if (current != null)
current.EndEdit();
}
}
}

调用代码