简体   繁体   中英

Executing SQL Function Using Linq

I have created a function in MSSQL 2005 and I want to run this function using linq. My function has 2 parameters. The definition is seen below:

USE [MobileGateway]
GO
/****** Object:  UserDefinedFunction [dbo].[Fn_GetNoLocationAddress]    Script Date: 11/07/2012 08:27:58 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER FUNCTION [dbo].[Fn_GetNoLocationAddress] 
(   
    -- Add the parameters for the function here
    @Site nvarchar(255),
    @ReceivedDate int
)
RETURNS @noLocationAddress TABLE (

RequestID int NOT NULL,
Barcode varchar(50) NOT NULL,
AdrID int NOT NULL,
Name varchar(50) NOT NULL,
Street varchar(50) NOT NULL,
HouseNo varchar(4) NOT NULL,
Postal varchar(8) NOT NULL,
City varchar(50) NOT NULL,
Country varchar(50) NOT NULL,
Latitude varchar(50) NOT NULL,
Longitude varchar(50) NOT NULL,
ReveivedDate datetime NOT NULL
)
AS 
BEGIN
    -- Add the SELECT statement with parameter references here
INSERT INTO @noLocationAddress 
SELECT     TOP (100) PERCENT Request1.RequestID, TrackIT.dbo.Sending.Barcode, TrackIT.dbo.Address_View.AdrID, TrackIT.dbo.Address_View.Name, 
                      TrackIT.dbo.Address_View.Street, TrackIT.dbo.Address_View.HouseNo, TrackIT.dbo.Address_View.Postal, TrackIT.dbo.Address_View.City, 
                      TrackIT.dbo.Address_View.Country, Request1.Latitude, Request1.Longitude, Request1.ReceivedDate
FROM         (SELECT DISTINCT RequestID, LTRIM([Content]) AS Barcode, Latitude, Longitude, ReceivedDate
                       FROM          dbo.RequestWithLocation
                       WHERE      (Site LIKE @Site) AND ([Content] <> '') AND (AddressID = '0') AND (ReceivedDate > DATEADD(day, -@ReceivedDate, GETDATE()))) AS Request1 INNER JOIN
                      TrackIT.dbo.Sending ON Request1.Barcode = TrackIT.dbo.Sending.Barcode INNER JOIN
                      TrackIT.dbo.Address_View ON TrackIT.dbo.Sending.DeliveryAdrID = TrackIT.dbo.Address_View.AdrID

ORDER BY TrackIT.dbo.Address_View.AdrID

RETURN

END

As you can see I have 2 parameters and I'm returning a table with the information. But I need to use linq for executing the this function. Can anyone help? thanks

I am assuming that you are using a dbml (linq to sql) file.

Drag drop your User defined function from the server explorer in visual studio into your dbml.

Then from the datacontext object of your dbml you can call the function directly.

For example if your dbml file name is xyz.dbml then your datacontext object's name would be 'XyzDataContext', unless you have changed it.

Then try this.

XyzDataContext db = new XyzDataContext();
List<Fn_GetNoLocationAddressResult> = db.Fn_GetNoLocationAddress("site", 25).ToList();

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