简体   繁体   中英

How do I use a SQL function from C# code section using Entity Framework in MVC 4

I have a SQL Function like this, named AgeCalc

USE [DB_test]
GO
/****** Object:  UserDefinedFunction [dbo].[AgeCalc]    Script Date: 01-Jul-16 3:31:52 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[AgeCalc]()
RETURNS NUMERIC(9,2)
AS
BEGIN
    DECLARE @birth_date DATETIME
    DECLARE @today_date DATETIME
    DECLARE @age NUMERIC(9,2)
    SELECT @birth_date = DofB FROM dbo.Table_formula
    SELECT @today_date = InpDate FROM dbo.Table_formula

    RETURN CONVERT(NUMERIC(9,2), @birth_date -@today_date )
END

How can I call this AgeCalc function from my C# code end? I have called a procedure in this way

DBC dbc = new DBC();
dbc.Database.SqlQuery<tbl_user>("inT_pop @id", new SqlParameter("@id", 2)).ToList();

Here inT_pop is my procedure name, is the same way I can call a function too?

YourContext.CreateQuery<bool>(
"SELECT VALUE YourModel.Store.UserDefinedFunction(@Parameter1) FROM {1}",
new ObjectParameter("Parameter1", Parameter1Value)).First();

Hope this might be helpful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM