I'm new to Entity Framework, so I want to execute a procedure, but the class or entity without the data annotation Key
, would that be possible? My stored procedure returns a single list of decimals, I read some examples and them used the SqlQuery<TEntity>()
, but it causes an error that the key is not defined for this entity, can you help me please?
This is my example:
public class ReturnBill
{
public decimal Discount { get; set; }
public decimal Total { get; set; }
public decimal IVA { get; set; }
public decimal Extras { get; set; }
}
This is how I call the stored procedure with SqlQuery<TEntity>()
:
this.oContext.Database.SqlQuery<T>(SQLCommand, sqlParams.ToArray()).ToList();
this is my store procedure
create procedure QUERY.SP_GET_TOTAL_MONTHLY_BILL (
@vMonth int,
@vYear int
)
AS
begin
IF OBJECT_ID(N'tempdb.QUERY.#TEMPBILL')IS NOT NULL
BEGIN
drop table QUERY.#TEMPBILL;
END
SELECT
SUM(bDiscounts) as Discount,SUM(bTotal) as Total,SUM(bIVA) as IVA,SUM(bExtras) as Extras INTO QUERY.#TEMPBILL
FROM dbo.BILLS
WHERE bMonths = @vMonth and bYear = @vYear;
SELECT
*
FROM QUERY.#TEMPBILL;
end;
and this is the way that I try to get the procedure
enuConnection eConn = enuConnection.DBCounts;
List<SqlParameter> pParam = new List<SqlParameter>(){
new SqlParameter("@vMonth",SqlDbType.Int,4){Value = 7},
new SqlParameter("@vYear",SqlDbType.Int,4){Value = inAnnio}}
};
clsUnitOfWork<ReturnBill> oUnitOfWork = new clsUnitOfWork<ReturnBill>(eConexion);
var oList = oUnitOfWork.RepositoryEntity.ExecuteOwnProcedure("QUERY.SP_GET_TOTAL_MONTHLY_BILL", pParam);
So the body of ExecuteOwnProcedure is:
public object ExecuteOwnProcedure(string sNameProcedure, List<SqlParameter> sqlParams)
{
string SQLCommands = "";
int counter = 0;
object oResult = null;
try
{
SQLCommands = sNameProcedure + " ";
Dictionary<string, object> oReturn = new Dictionary<string, object>();
foreach (var _param in sqlParams)
{
SQLCommands += _param.ParameterName;
counter++;
if (_param.Direction == System.Data.ParameterDirection.Output)
{
SQLCommands += " OUTPUT ";
}
if (counter < sqlParams.Count())
{
SQLCommands += ", ";
}
}
oResult = this.oContext.Database.SqlQuery<T>(SQLCommands, sqlParams.ToArray()).ToList();
}
catch (Exception e)
{
thrown new Exception(e.Message);
}
return oResult;
}