我新建了一个Linq to SQl Classes项,命名为ETC.dbml。系统会默认生成ETCDataContext。
系统在执行ETCDataContext.SubmitChanges()时返回是空值,这样用户就无法知道执行结果到底是成功还是失败。所以决定用扩展方法对ETCDataContext作个扩展。
代码如下,此代码中包含DataAccessComponent类,此类主要作配置ConnectionString。其它所有涉及到DataContext操作的类都继承自此类,并使用此类实例化DataContext。此类的下边的静态Extensions类是我对ETCDataContext扩展方法。
注意,扩展方法要求是静态类,传入的参数是扩展的对象,且在参数前加this关键字。
public class DataAccessComponent
{
/// <summary>
/// Get connection string of databse
/// </summary>
protected ETCDataContext EtcDataContext
{
get
{
return new ETCDataContext(ConfigurationManager.ConnectionStrings["etcConnectionString"].ConnectionString);
}
}
}
/// <summary>
/// 扩展方法类
/// </summary>
public static class Extensions
{
/// <summary>
/// 更新并返回结果
/// </summary>
/// <param name="etcDataContext"></param>
/// <returns>true:正确;false:错误</returns>
public static bool SubmitChangesWithResult(this ETCDataContext etcDataContext)
{
bool result = false;
try
{
etcDataContext.SubmitChanges();
result = true;
}
catch (Exception ex)
{
result = false;
}
return result;
}
}
{
/// <summary>
/// Get connection string of databse
/// </summary>
protected ETCDataContext EtcDataContext
{
get
{
return new ETCDataContext(ConfigurationManager.ConnectionStrings["etcConnectionString"].ConnectionString);
}
}
}
/// <summary>
/// 扩展方法类
/// </summary>
public static class Extensions
{
/// <summary>
/// 更新并返回结果
/// </summary>
/// <param name="etcDataContext"></param>
/// <returns>true:正确;false:错误</returns>
public static bool SubmitChangesWithResult(this ETCDataContext etcDataContext)
{
bool result = false;
try
{
etcDataContext.SubmitChanges();
result = true;
}
catch (Exception ex)
{
result = false;
}
return result;
}
}