采用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. 记录下自己常用的全框架HTML代码

    纯粹记录下,没有任何意义. 也不推荐使用 <frameset rows="> <frame src=" name="topFrame" scr ...

  2. js正则表达式的应用

    JavaScript表单验证email,判断一个输入量是否为邮箱email,通过正则表达式实现. //检查email邮箱 function isEmail(str){ var reg = /^([a- ...

  3. JAVA程序员应该看的15本书的电子版

    转载▼ 转载自:http://blog.sina.com.cn/s/blog_8297f0d00100v5ew.html 作为Java程序员来说,最痛苦的事情莫过于可以选择的范围太广,可以读的书太多, ...

  4. AsyncTask应用示例

    package com.example.testdemo; import java.io.ByteArrayOutputStream; import java.io.IOException; impo ...

  5. SVN-001

    1.cd到指定目录: 2.执行:svn cleanup:

  6. iOS - xib中关于拖拽手势的潜在错误

    iOS开发拓展篇—xib中关于拖拽手势的潜在错误 一.错误说明 自定义一个用来封装工具条的类 搭建xib,并添加一个拖拽的手势. 主控制器的代码:加载工具条 封装工具条以及手势拖拽的监听事件 此时运行 ...

  7. oracle中怎么用normal方式登录怎么自定义用户名和密码

    1.首先要创建一个用户.必须使用有最高权限的用户来创建,语句如下: create user shopping identified by 123456;--创建shopping用户,密码123456 ...

  8. oracle11g+win7没有listener服务

    今天在win7上面安装oracle11g的时候,配置了listener后,lsnrctl start报错. 查看服务,也没有发现listener服务. 各位有没有遇见过这个情况啊!!!!!

  9. C# Timer自带定时器

    官方文档 https://msdn.microsoft.com/zh-cn/library/system.timers.timer.aspx using System; using System.Ti ...

  10. JS常用函数与方法

    //当页面关闭时触发 window.onbeforeunload = function() { alert('关闭了吧'); } //关闭窗口(弹出式窗口) parent.window.close() ...