表值函数和实体框架

本文关键字:实体 框架 函数 | 更新日期: 2023-09-27 18:29:03

我正试图用实体框架执行TVF,但由于某种原因,它根本不起作用。也许任何人都可以帮我解决问题。

以下是代码示例:

这就是功能:

CREATE FUNCTION [dbo].[udf_profileSearch]
(@keywords NVARCHAR(3000))
RETURNS @results TABLE 
(
    [Id] [int] NULL,
    [SubCategoryId] [int] NULL,
    [UserId] [int] NULL,
    [SmallDescription] [nvarchar](250) NULL,
    [DetailedDescription] [nvarchar](500) NULL,
    [Graduation] [nvarchar](140) NULL,
    [Experience] [nvarchar](500) NULL,
    [IsChat] [bit] NULL,
    [IsEmail] [bit] NULL,
    [MinuteCost] [decimal](18, 2) NOT NULL,
    [TestimonyRate] [int] NULL,
    [TestimonyQuantity] [int] NULL,
    [StatusId] [int] NULL
)
AS
BEGIN
IF(@keywords != '')
    BEGIN
        insert @results
            SELECT p.Id, p.SubCategoryId, p.UserId, p.SmallDescription, p.DetailedDescription, p.Graduation, 
                        p.Experience, p.IsChat, p.IsEmail, p.MinuteCost, p.TestimonyRate, p.TestimonyQuantity, 
                        p.StatusId FROM 
            Profile p inner join ProfileSearchKeyword psk
            ON p.Id = psk.ProfileId
            WHERE CONTAINS(psk.*,@keywords)
    END
ELSE 
    BEGIN
        insert @results
            SELECT p.* FROM 
            Profile p inner join ProfileSearchKeyword psk
            ON p.Id = psk.ProfileId
    END
RETURN
END

我在我的DbContext文件(名为EAjudaContext)中有这个

[EdmFunction("eAjudaConnection", "udf_profileSearch")]
    public virtual IQueryable<Profile> udf_profileSearch(string keywords)
    {
        var keywordsParameter = keywords != null ?
            new ObjectParameter("keywords", keywords) :
            new ObjectParameter("keywords", typeof(string));
        return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<Profile>("eAjudaConnection.udf_profileSearch(@keywords)", keywordsParameter);
    }

这就是我通过LINQ 调用函数的方式

var result = from ps in eAjudaCtx.udf_profileSearch("query") select ps

我得到了这个错误:


'eAjudaConnection.udf_profileSearch' cannot be resolved into a valid type or function.

Any ideas on what I'm missing? I've tried pretty much every tip I found on google, but none solved my problem.

If you need to see any piece of code not included here, just ask and I'll add it.

表值函数和实体框架

[Tested] using:

Install-Package EntityFramework.CodeFirstStoreFunctions

为输出结果声明一个类:

public class MyCustomObject
{
   [Key]
   public int Id { get; set; }
   public int Rank { get; set; }
}

在DbContext类中创建一个方法

[DbFunction("MyContextType", "SearchSomething")]
public virtual IQueryable<MyCustomObject> SearchSomething(string keywords)
{
   var keywordsParam = new ObjectParameter("keywords", typeof(string)) 
                           { 
                              Value = keywords 
                            };
    return (this as IObjectContextAdapter).ObjectContext
    .CreateQuery<MyCustomObject>(
     "MyContextType.SearchSomething(@keywords)", keywordsParam);
}

添加

public DbSet<MyCustomObject> SearchResults { get; set; }

到您的DbContext类

添加overriden OnModelCreating方法:

modelBuilder.Conventions
.Add(new CodeFirstStoreFunctions.FunctionsConvention<MyContextType>("dbo"));

现在您可以与表值函数如下:

CREATE FUNCTION SearchSomething
(   
    @keywords nvarchar(4000)
)
RETURNS TABLE 
AS
RETURN 
(SELECT KEY_TBL.RANK AS Rank, Id
FROM MyTable 
LEFT JOIN freetexttable(MyTable , ([MyColumn1],[MyColumn2]), @keywords) AS KEY_TBL      
ON MyTable.Id = KEY_TBL.[KEY]  
WHERE KEY_TBL.RANK > 0   
)
GO

这是一篇关于实体框架的新功能的非常好的文章,这些功能为表值UDF提供了直接支持。MSDN关于实体框架中表值函数支持的博客。

为了更深入,本文提供了重要的细节。EDM和存储在LINQ中公开的功能。

最近支持表值UDF的一大优点是支持全文搜索功能。在这里阅读更多信息:涉及数据库对象的全文搜索功能。

这是一种将表参数发送到函数并返回表值函数值的方法。

C#:

var fooDataTable = new DataTable();
var ids = new List<FooDto>();
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<fn_Car_Result>
        ("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<CarFieldsDTO> { template };
return fields.AsQueryable();

其中dbDbContext

DTO:

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

SQL表值函数:

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
    )

用户定义的表格类型:

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