0

I have database function like this :

CREATE FUNCTION [dbo].[FuelByOrganization] 
    (@organziationId INT = 0)
RETURNS TABLE
AS 
    RETURN 
        SELECT 
            dbo.FuelDelivery.ID AS FuelDeleveryId, 
            dbo.Contracts.ContractNumber AS ContractLetterNumber, 
        FROM  
            dbo.FuelDelivery 
        INNER JOIN  
            dbo.Contracts ON dbo.FuelDelivery.ContractID = dbo.Contracts.ID
        WHERE 
            dbo.Contracts.OrganizationId = @organziationId;

I want to run this command while I am migrating my database. I am using a code-first approach, how can I create this function during my migrations?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • Just for ensure, Why you add such function if you can create LINQ equivalent of the same function. – Svyatoslav Danyliv Jul 05 '21 at 13:05
  • You could use a similar approach as a recommended approached for stored procs: https://stackoverflow.com/questions/20715292/create-stored-procedures-using-entity-framework-code-first – Ben Osborne Jul 05 '21 at 13:54
  • @SvyatoslavDanyliv because I want to do that in database side for performance issue .I do not want to return all the data I want some specific one. – Mustafa Taeb Jul 06 '21 at 03:45
  • 1
    @MustafaTaeb, if you create IQuryable methothod with custom projection, you will return only needed data. Your SP can be easily replaced by LINQ. – Svyatoslav Danyliv Jul 06 '21 at 05:43

2 Answers2

1

Alternative answer: If you plan you use such function in LINQ queries - do not create such simple Stored Procedures, but replace them with IQueryable methods. Then you can combine IQueryable with other LINQ queries.

public static class BusinessFunctions
{
    public static IQueryable<FuelByOrganizationResult> FuelByOrganization(this MyContext ctx, int? organziationId = default)
    {
        var query = 
            from fd in ctx.FuelDelivery
            from c in fd.Contracts
            select new {
                fd,
                c
            };

        if (organziationId != bull)
            query = query.Where(q => q.c.OrganizationId = organziationId);

        return query.Select(q =>
            new FuelByOrganizationResult
            {
                FuelDeleveryId = q.fd.Id,
                ContractNumber = q.c.ContractNumber
            });
    }
}
Svyatoslav Danyliv
  • 21,911
  • 3
  • 16
  • 32
0

You can run your script in the main function of your program.

 public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateHostBuilder(args).Build();
            // Run your script here
            host.Run();          
        }
        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }