在实体框架中调用标量值函数
本文关键字:标量 函数 调用 实体 框架 | 更新日期: 2023-09-27 18:05:30
如何在实体框架6中调用标量函数?我尝试了以下代码
using (MhEntities DContext = new MhEntities())
{
var Account_IdParameter = Account_Id.HasValue ? new ObjectParameter("Account_Id", Account_Id) : new ObjectParameter("Account_Id", typeof(long));
string res = ((IObjectContextAdapter)DContext).ObjectContext.CreateQuery<string>("MoneyforHealthEntities.Fn_LEVEL0_Acount_Id", Account_IdParameter).FirstOrDefault();
return Convert.ToInt64(res);
}
不需要使用ObjectContext
来完成此操作。此外,我不认为你可以简单地传递函数的名称,你需要给它完整的,有效的SQL。
所以我会尝试这样做:
using (MhEntities DContext = new MhEntities())
{
string res = DContext.Database.SqlQuery<string>("SELECT MoneyforHealthEntities.Fn_LEVEL0_Acount_Id(@p0)", Account_Id).FirstOrDefault();
return Convert.ToInt64(res);
}
由于您没有提供有关您正在使用的数据库或确切函数定义的任何细节,因此上述可能需要进一步调整。但它至少应该给你一个基本的概念。
DateTime ServerTime = new ContextDbEntities().Database.SqlQuery<DateTime>("Select getdate();").FirstOrDefault();
MessageBox.Show(ServerTime.ToString());
所有的答案都是正确的,但如果有人使用stored procedure
,它需要在函数导入上进行编辑:
1. 右键单击function
,然后单击edit
。
2. 在edit function Import
窗口上。
3.在returns a collection
区段上选择Scaler
。
4. 最后,单击ok并保存模型。
在我的示例中,我调用一个Insert存储过程,它返回一个字符串值。
using (DbModel db = new DbModel())
{
string result = db.storedprocedureName(value1,value2).FirstOrDefault();
return result;
}