Support for Table Valued Functions in EF6 Code First?

前端 未结 6 857
走了就别回头了
走了就别回头了 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:33

    I have developed a library for this functionality. You can review my article on UserTableFunctionCodeFirst. You can use your function without writing SQL query.

    Update

    First of all you have to add reference to the above mentioned library and then you have to create parameter class for your function. This class can contain any number and type of parameter

    public class TestFunctionParams
        {
            [CodeFunctionAttributes.FunctionOrder(1)]
            [CodeFunctionAttributes.Name("id")]
            [CodeFunctionAttributes.ParameterType(System.Data.SqlDbType.Int)]
            public int Id { get; set; }
        }
    

    Now you have to add following property in your DbContext to call function and map to the property.

    [CodeFunctionAttributes.Schema("dbo")] // This is optional as it is set as dbo as default if not provided.
            [CodeFunctionAttributes.Name("ufn_MyFunction")] // Name of function in database.
            [CodeFunctionAttributes.ReturnTypes(typeof(Customer))]
            public TableValueFunction CustomerFunction { get; set; }
    

    Then you can call your function as below.

    using (var db = new DataContext())
                {
                    var funcParams = new TestFunctionParams() { Id = 1 };
                    var entity = db.CustomerFunction.ExecuteFunction(funcParams).ToList();
                }
    

    This will call your user defined function and map to the entity.

提交回复
热议问题