采用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();
}
}
}

调用代码

CSLA.Net学习(2)的更多相关文章

  1. CSLA.Net学习(3)INotifyPropertyChanged和IDataErrorInfo

    今天晕晕糊糊的看CSLA.net,希望能找到验证数据正确性的方法,还是摸索出了INotifyPropertyChanged, IDataErrorInfo接口的使用方法,通过INotifyProper ...

  2. CSLA框架的codesmith模板改造

    一直有关注CSLA框架,最近闲来无事,折腾了下,在最新的r3054版本基础上修改了一些东西,以备自己用,有兴趣的园友可以下载共同研究 1.添加了默认的授权规则 如果是列表对象则生成列表权限,User的 ...

  3. CSLA的项目结构(一)

    由于我也是边看边学,在很多概念不是很清晰的情况下,也不好将书中的大段内容全部摘抄过来,所以结合项目源码先分析再总结,就成目前比较可行方案,第一篇先从项目结构入手. 项目源码下载后,主要的功能集中在Co ...

  4. [King.yue]关于CSLA框架的一些看法

    CSLA.Net 是一个有帮助的成熟开发框架,但不适于初学者.该框架支持在任何地方.任何时间创建对象,值得我们花时间去学习了解这一框架.CSLA.Net 框架设计的业务对象,支持对完全透明的数据源进行 ...

  5. 《使用CSLA 2019:CSLA .NET概述》原版和机译文档下载

    自己从作者官方网站上(http://www.cslanet.com/)下载的免费版.PDF文档,又使用有道付款翻译的,供大家下载学习,文档中是对CSLA.NET4.9版本的介绍. 下载链接:http: ...

  6. [推荐]大量 Blazor 学习资源(二)

    继上一篇<[推荐]大量 Blazor 学习资源(一)>之后,社区反应不错,但因个人原因导致这篇文章姗姗来迟,不过最终还是来了!这篇文章主要收集一些常用组件.书籍和电子书. 资料来源:htt ...

  7. 从直播编程到直播教育:LiveEdu.tv开启多元化的在线学习直播时代

    2015年9月,一个叫Livecoding.tv的网站在互联网上引起了编程界的注意.缘于Pingwest品玩的一位编辑在上网时无意中发现了这个网站,并写了一篇文章<一个比直播睡觉更奇怪的网站:直 ...

  8. Angular2学习笔记(1)

    Angular2学习笔记(1) 1. 写在前面 之前基于Electron写过一个Markdown编辑器.就其功能而言,主要功能已经实现,一些小的不影响使用的功能由于时间关系还没有完成:但就代码而言,之 ...

  9. ABP入门系列(1)——学习Abp框架之实操演练

    作为.Net工地搬砖长工一名,一直致力于挖坑(Bug)填坑(Debug),但技术却不见长进.也曾热情于新技术的学习,憧憬过成为技术大拿.从前端到后端,从bootstrap到javascript,从py ...

随机推荐

  1. 基于Nginx反向代理及负载均衡

    基于Nginx反向代理及负载均衡 参考:http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass 只要没有被启用,默认就是 ...

  2. 【matlab】图像去噪的代码测试

    %% 自己设置频域的滤波窗口 girl=imread('F:\Users\*****\Pictures\CGS_stripe1.bmp'); girl=rgb2gray(girl); girl=im2 ...

  3. 使用ADO实现BLOB数据的存取 -- ADO开发实践之二

    使用ADO实现BLOB数据的存取 -- ADO开发实践之二 http://www.360doc.com/content/11/0113/16/4780948_86256633.shtml 一.前言 在 ...

  4. Java类的设计----关键字super

    关键字super 在Java类中使用super来引用父类的成分 super可用于访问父类中定义的属性 super可用于调用父类中定义的成员方法 super可用于在子类构造方法中调用父类的构造方法 su ...

  5. JVM学习(一)

    JVM自身的物理结构:

  6. 多线程的学习与GDI的学习

    今天又是一周的周五,感觉过的好快,我感觉不是期盼周末的到来,而是感觉现在已经习惯啦每天坐在这里敲代码,其实我是一个性格非常开朗的女生,现在不知道为什么感觉默默地坐在自己位置上面敲代码成为了我习以为常的 ...

  7. java基础---->多个排序的拓展

    根据一些特定的规则,我们可以利用java的反射机制做到很有趣的封装. java的排序封装 一.定义一些comparator AmountComparatorAsc:amount升序 package c ...

  8. 开源的PaaS方案:在OpenStack上部署CloudFoundry (五)常见问题

    部署CloudFoundry可能遇到的问题 1. Bosh 报告 OpenStack API Request Entity Too Large error 解决办法,修改/etc/nova/api-p ...

  9. JavaBean与Map<String,Object>相互转换

    一.为什么要实现javaBean与Map<String,Object>相互转换 Spring中的BaseCommandController对象可以将传递过来的参数封装到一个JavaBean ...

  10. PHP关于验证

    验证身份证号码 /** * 验证身份证号 * @param $vStr * @return bool */ private function _isCreditNo($vStr) { $vCity = ...