SQL Server EF Core Views and SQL Parameters

4si2a6ki  于 2022-12-22  发布在  其他
关注(0)|答案(1)|浏览(161)

I have created a view on SQL Server which produces a report for monthly totals. The view has been added to my DB Context and mapped successfully, therefore I am in a position where I can successfully get the results of my view as follows:

var list = db.MonthlyTotals.ToList();

However, I need to be able to restrict between dates and therefore needs to pass in some parameters for a start and end date.
Is this possible with either EF Core 6 or 7? Or do I need to use stored procedures instead?

ep6jt1vc

ep6jt1vc1#

I have created a view...I need to be able to restrict between dates and therefore needs to pass in some parameters for a start and end date...Is this possible with either EF Core 6 or 7?
Views don't use parameters, that's by design of the SQL Server Engine, and has nothing to do with whatever ORM you use, such as EF Core. If you really want to use parameters, then use stored procedures.
But the good news is, your use case is simple enough that you shouldn't need parameters anyway. Like Gert suggested in the comments, just use a Where clause against your view instead.
You can achieve this in C# with LINQ's method syntax like so:

var list = db.MonthlyTotals
    .Where(mt => mt.YourDateColumn >= someDateVariable && my.YourDateColumn < someOtherDateVariable)
    .ToList();

There's also query syntax with LINQ, which more closely resembles T-SQL code, but in my opinion is less intuitive in the context of C# as opposed to method syntax.

相关问题