Linq to Sql学习总结3
存储过程:
关系数据库中的存储过程在实体类中映射为具体的方法,直接将存储过程拖动到对应的dbml设计视图中即可,如图:
在将存储过程拖入dbml设计视图中时,系统执行了如下命令:
SET FMTONLY ON;--表示只获取结果集的元数据(即相关列名 ) exec sp_Name SET FMTONLY OFF;
方法的返回对象根据获取到的元数据确定(在dbml的cs文件中定义了一个部分实体类用于返回对象,实体类属性为获取到的元数据,这也说明了在查询的存储过程的句法中的操作是属于linq to object的)。
存储过程方法定义:
--单结果集存储过程定义
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.sp_SingleResultSet")]
public ISingleResult<sp_SingleResultSetResult> sp_SingleResultSet()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((ISingleResult<sp_SingleResultSetResult>)(result.ReturnValue));
}
--多结果集存储过程定义
[Function(Name="dbo.sp_multiresultset")]
//定义返回值类型
[global::System.Data.Linq.Mapping.ResultType(typeof(Customers))]
[global::System.Data.Linq.Mapping.ResultType(typeof(Employees))]
//返回类型由ISingleResult<sp_SingleResultSetResult>改为IMultipleResults
public IMultipleResults sp_multiresultset()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return (IMultipleResults)(result.ReturnValue);
}
单结果集存储过程:
var 单结果集存储过程 =
from c in ctx.sp_singleresultset()
where c.CustomerID.StartsWith("A")
select c;
带参数存储过程:
//带参数存储过程,Linq会将procedure中的output参数定义为linq to sql类中的ref参数
create proc [dbo].[sp_withparameter]
@customerid nchar(5),
@rowcount int output
as
set nocount on
set @rowcount = (select count(*) from customers where customerid = @customerid)
//方法调用
int? rowCount = -1;
ctx.sp_WithParameter("",ref rowCount);
带返回值的存储过程:
//带返回值的存储过程,Linq会将procedure中的返回值定义为linq to sql类方法(返回实体集的方法定义)的返回值
create proc [dbo].[sp_withreturnvalue]
@customerid nchar(5)
as
set nocount on
if exists (select 1 from customers where customerid = @customerid)
return 101
else
return 100
//方法调用
Response.Write(ctx.sp_withreturnvalue(""));
多结果集存储过程:
//多结果集存储过程(生成的linq to sql类只返回了第一个结果集的实体) //需要手动修改返回实体结果集的方法定义 create proc [dbo].[sp_multiresultset] as set nocount on select * from customers select * from employees //方法调用 var qMultiResultSet = ctx.sp_multiresultset(); var qCustomersSet = qMultiResultSet.GetResult<Customers>(); var qEmployeesSet = qMultiResultSet.GetResult<Employees>();
为实体类配置增删改行为:
1、先定义用于增删改的存储过程,并映射成相应的方法;
2、在dbml设计视图中为实体类配备相应存储过程方法用于增删改行为,如图:
配置完成之后再dbml中cs文件中生成如下方法:
#region 为实体类的增删改行为配置的方法(方法使用存储过程生成)
private void InserttbGuestBook(tbGuestBook obj)
{
this.sendmessage(obj.UserName, obj.Message);
}
private void UpdatetbGuestBook(tbGuestBook obj)
{
this.replymessage(((System.Nullable<int>)(obj.ID)), obj.Reply);
}
private void DeletetbGuestBook(tbGuestBook obj)
{
this.delmessage(((System.Nullable<int>)(obj.ID)));
}
#endregion
调用方式如下:
ctx.delmessage(Convert.ToInt32(e.CommandArgument.ToString()));
ctx.replymessage(Convert.ToInt32(e.CommandArgument.ToString()), ((TextBox)e.Item.FindControl("tb_Reply")).Text);
//在配置更新行为时,对于传入参数有两个可选值原始值(original)和当前值(current),原始值表示更新之前的值,当前值表示当前需要更新的值
//在配置类行为的时候,oldusername使用原始值,newusername使用当前值
ctx.modiusername("admin", "notadmin");
