Support for Table Valued Functions in EF6 Code First?

前端 未结 6 862
走了就别回头了
走了就别回头了 2021-02-07 10:03

Is it possible to call a TVF in EF6 Code First?

I started a new project using EF6 Database first and EF was able to import a TVF into the model and call it just fine. <

6条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-07 10:15

    [Tested] using:

    Install-Package EntityFramework.CodeFirstStoreFunctions
    

    Declare a class for output result:

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

    Create a method in your DbContext class

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

    Add

    public DbSet SearchResults { get; set; }
    

    to your DbContext class

    Add in the overriden OnModelCreating method:

     modelBuilder.Conventions.Add(new FunctionsConvention("dbo"));
    

    And now you can call/join with a table values function like this:

    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
    

提交回复
热议问题