Table Valued Function and Entity Framework

前端 未结 3 1329
生来不讨喜
生来不讨喜 2021-02-05 13:28

I\'m trying to execute an TVF with Entity Framework and for some reason it just doesn\'t work. Maybe anyone out there can help me see the problem.

Here are the code samp

3条回答
  •  渐次进展
    2021-02-05 14:09

    This is a way to send table parameter to function and return values of table valued function.

    C#:

    var fooDataTable = new DataTable();
    var ids = new List();
    if (ids.Count > 0)
    {
        fooDataTable.Columns.Add("ID", typeof(int));
        fooDataTable.Columns.Add("CarNumber");
        fooDataTable.Columns.Add("ArriveDate", typeof(DateTime));                
    
        foreach (var car in ids)
        {
            fooDataTable.Rows.Add(car?.ID, car?.CarNumber, car?.ArriveDate);
        }
    }
    
    SqlParameter cdIDs = new SqlParameter("@ListToCalc", SqlDbType.Structured);
    cdIDs.Value = fooDataTable;
    cdIDs.TypeName = "tp_CarList";
    
    var template = new CarFieldsDTO
    {
        Fields = db.Database.SqlQuery
            ("SELECT * FROM dbo.fn_Car(@ListToCalc)", cdIDs)
                .Select(field => new CarFieldsDTO
                {
                    ID = field.ID,
                    CarNumber = field.CarNumber,
                    ArriveDate = field.ArriveDate,                    
                }).ToList()
    };
    
    var fields = new List { template };
    return fields.AsQueryable();
    

    Where db is DbContext.

    DTO:

    public class CarFieldsDTO
    {        
        public int ID { get; set; }
    
        public string CarNumber { get; set; }
    
        public DateTime? ArriveDate { get; set; }
    
        public IEnumerable Fields { get; set; }
    }
    

    SQL table valued function:

    ALTER  FUNCTION [dbo].[fn_Car]
    (
          @ListToCalc tp_CarList READONLY
    )
    RETURNS TABLE
    AS
        RETURN
        (
            SELECT l.ID
                   , l.CarNumber
                   , l.ArriveDate
            FROM @ListToCalc l
            INNER JOIN Stations as sf ON sf.ID = l.id_StationFrom
        )
    

    User defined Table Type:

    CREATE TYPE [dbo].[tp_CarList] AS TABLE(
        [ID] [int] NOT NULL,
        [CarNumber] [varchar](12) NULL,
        [ArriveDate] [datetime] NULL    
    )
    GO
    

提交回复
热议问题