EF Core 5.0 is round the corner

EF Core 5.0 is in flux and is slated to be released along with .NET 5.0. One thing to note is that EF Core 5.0 will not run on .NET Framework, unlike its predecessors. I personally think, this is good news as it is time to step up the ante and move out of the .NET legacy Framework  and onto the .NET Core ecosystem. That said, the plan is to maintain .NET Standard 2.1 compatibility through the final release.

Those of you who jumped on the EF Core bandwagon know full well that EF Core has come a long way from the time of its inception back in June 2016. Since then, there have been numerous incremental updates by the development team currently led by Arthur Wickers (formerly Diego Vega and Rowan Miller) along with the support of Andriy Svyryd, Brice Lambson, Jeremy Likness, IaJones, Maurycy Markowski, Shay Rojansky, Smit Patel, Erik Jensen and numerous OSS contributors around the globe who have worked diligently to completely transform this ORM. The capabilities and ease of use of EF Core has made its adoption compelling enough in modern software development ranging from desktop, web, mobile and UWP environments and across platforms.

What’s new in EF Core 5.0

  • Split Queries for related Collections

The following query will retrieve two levels of related collections using the Include like so:

var artists = context.Artists
    .Include(e => e.Albums).ThenInclude(e => e.Tags)
    .ToList();

The following SQL gets generated by default:

SELECT "a"."Id", "a"."Name", "t0"."Id", "t0"."ArtistId", "t0"."Title", "t0"."Id0", "t0"."AlbumId", "t0"."Name"
FROM "Artists" AS "a"
LEFT JOIN (
    SELECT "a0"."Id", "a0"."ArtistId", "a0"."Title", "t"."Id" AS "Id0", "t"."AlbumId", "t"."Name"
    FROM "Album" AS "a0"
    LEFT JOIN "Tag" AS "t" ON "a0"."Id" = "t"."AlbumId"
) AS "t0" ON "a"."Id" = "t0"."ArtistId"
ORDER BY "a"."Id", "t0"."Id", "t0"."Id0"

With the new AsSplitQuery API, the behavior can be altered as follows:

var artists = context.Artists
    .AsSplitQuery()
    .Include(e => e.Albums).ThenInclude(e => e.Tags)
    .ToList();

EF Core will generate the following SQL queries:

SELECT "a"."Id", "a"."Name"
FROM "Artists" AS "a"
ORDER BY "a"."Id"

SELECT "a0"."Id", "a0"."ArtistId", "a0"."Title", "a"."Id"
FROM "Artists" AS "a"
INNER JOIN "Album" AS "a0" ON "a"."Id" = "a0"."ArtistId"
ORDER BY "a"."Id", "a0"."Id"

SELECT "t"."Id", "t"."AlbumId", "t"."Name", "a"."Id", "a0"."Id"
FROM "Artists" AS "a"
INNER JOIN "Album" AS "a0" ON "a"."Id" = "a0"."ArtistId"
INNER JOIN "Tag" AS "t" ON "a0"."Id" = "t"."AlbumId"
ORDER BY "a"."Id", "a0"."Id"
  • Index Attribute
  • Improved Query Translation Exceptions
  • Exclude OnConfiguring when scaffolding
  • Translations for FirstOrDefault on strings

C#

context.Customers.Where(c => c.ContactName.FirstOrDefault() == 'A').ToList();

SQL

SELECT [c].[Id], [c].[ContactName]
FROM [Customer] AS [c]
WHERE SUBSTRING([c].[ContactName], 1, 1) = N'A'
  • Simplification of Case blocks
  • Database collations

For a detailed description of new features/announcements, please refer to the following resources below:

Posted in Uncategorized | Leave a comment

How to add multiple rows to a table at once

Let’s face it, most of the apps in the galaxy we live in are data bound. I don’t write apps that use sockets and presumably most of you don’t either, correct?

Now, in our day to day lives, we generally use a database of sorts, may it be SQL Server, MySQL, Oracle, PostgreSQL etc. all of which are relational. You have heard the famous cliche, “There are multiple ways to skin a cat”. Well, let’s not go there…suffice it to say, there are many solutions to a problem.

Without rambling too much, let’s get to the point. What I have below is a simple Entity Relational Diagram. To illustrate my point, I am attempting to add records into the Composite table from Magazine, Article and Author tables like so.

INSERT INTO Composite (Magazine, Title, PublishedDate, AuthorName)
    (SELECT 
        m.[Name], 
        a.Title,
        a.PublishDate,
        au.[Name]
    FROM
        Magazine m 
        INNER JOIN Article a ON m.MagazineId = a.MagazineId
        INNER JOIN Author au ON a.AuthorId = au.AuthorId)

As you can see without repeating Insert Into…statement multiple times just like you would typically do, one can accomplish the same by using the Select statement to select the columns belonging to one or more tables.

 

 

 

 

 

 

 

 

Output from the newly inserted records in the Composite table:

Posted in SQL Server | Leave a comment

How to Extend Session in ASP.NET

If you are building a web app using “Forms” as a mode of authentication, there’s really not much to it when it comes to extending a session automatically.

What I am suggesting is that your web session will extend on its own so long as you have defined slidingExpiration attribute in your web.config file like so:

<authentication mode="Forms"> 
    <forms name=".ASPXAUTH" loginUrl="~/Login.aspx" timeout="20" slidingExpiration="true"></forms> 
</authentication>

Now, if you are using the authentication mode as “Windows“, there’s no support for the slidingExpiration attribute. For that, you can implement a solution in jQuery by simply creating a dummy HTML file and calling it anything you like. In the example below, I’ve named it AjaxDemo.html. See code below.

One thing to note here is that I am concatenating Date and Time when making an asynchronous call to AjaxDemo.html. This is done to ensure that a unique value is returned from the server. This step is crucial in extending the session timeout beyond its default threshold of 20 minutes.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-1.10.2.js"></script>

    <title>Session Timeout</title>
    <script type="text/javascript">
        var sessionDelay = 5000; // 5 seconds

        $(function () {
            $("#btnExtendSession").click( function () {
                keepAlive();              
            });
        });

        function keepAlive() {
            var d = new Date();
            $.get('AjaxDemo.html?=' + d.getTime(), function () {
                timer = setTimeout(keepAlive, sessionDelay);
                clearTimeout(timer);
            });
        }

    </script>
</head>
<body>
    <button id="btnExtendSession">Extend Session</button>
</body>
</html>

When you click on the button “Extend Session” and open dev tools,  inside the Network tab, you would notice a unique value appended to AjaxDemo.html’s query string. See below:

Hope you found the post useful.

Posted in jQuery | Leave a comment

What is Blazor and Why should you Use it!

Introduction:
According to Microsoft Docs, Blazor is a framework for building client-side web UI with .NET. It’s a feature of ASP.NET, the popular web development framework that extends the .NET developer platform with tools and libraries for building web apps.

Blazor lets you build interactive web UIs using C# instead of JavaScript. Blazor apps are composed of reusable web UI components implemented using C#, HTML and CSS. Both client and server code is written in C#, allowing  you to share code and libraries across projects.

If you’ve done any client-side development, I’m assuming you are familiar with Vue, Angular, React or Aurelia. Each one of these technologies is built on top of JavaScript. Blazor is different, in that it allows a developer to build compelling UIs by leveraging your existing C#, HTML and CSS skills without writing a single line of JavaScript code. This sounds pretty amazing, correct?

What Browsers can my Blazor code run on?
All modern browsers have Web Assembly baked in on which your code runs. The browsers range from Chrome, IE, Edge, Safari including browsers on mobile devices.

Flavour of Blazor:
Blazor comes with two architectures:

  • Client-side Blazor (WebAssembly)
  •  Server-side Blazor

As of this writing, Server-side Blazor is the most stable release and can be used in production.

Client-side Blazor (WebAssembly) is still in preview and is likely to RTM mid-2020. The way it works is that when the application runs, it loads all assets such as static files, assemblies including the run-time which is later converted to WebAssembly bytecode without requiring a connection to the server. While it offers some advantages such as the non-dependence on the server for your hosting needs and also be able to work in offline scenarios. However, when it comes to jobs that require compute-intensive operation, then this architecture may not be suitable for your needs.

Server-side Blazor in my opinion does foot the bill easily as it conforms to the lowest common denominator. In another words, you are not restricted to just the latest modern browsers to run your server-side blazor code, but you can also have your code run on some of the older browsers that don’t have web assembly on them.

Furthermore, the server-side Blazor app runs inside ASP.NET runtime. Any changes to the app are copied using a WebSocket connection through SignalR. As a result, all updates are streamed from the server in real-time.

Does Blazor have Plugins?
Unlike Blazor’s predecessor technologies such as Flash and Silverlight that required plugins to be installed on the client’s machine, Blazor on the other hand does not require any plugins due to the fact that it runs in Web Assembly which is baked in every modern browser.

Advantages of Blazor:
Following are some of the advantages of Blazor:

  • Leverage your C# skills to build full-stack Web app
  • Reuse libraries that are .NET Standard compliant
  • Runs on .NET runtime
  • Runs on any browser
  • Doesn’t require any plugins
  • Download razor components from NuGet
  • Highly performant
  •  Runs at near-native speed inside the browser on WebAssembly
  • Allows interoperability between Blazor and JavaScript code

What Tools can I use to create Blazor Apps:
Blazor apps can be developed using Visual Studio 2019 (all versions) with .NET Core 3.1 SDK or alternatively you can use a free online tool called Visual Studio Code (with latest C# extension).
Blazor Code Snippet:

The above is a plain vanilla code that you get out of the box. It illustrates the use of C# and HTML. Although, when building an enterprise app, you would want to decouple your business logic in a separate class and restrict the razor component to HTML and CSS just to keep it clean and maintain a separation of concerns.

If you want to know more about Blazor, please use the following resources from Microsoft.

Resources:

Posted in UI Framework | Leave a comment

How to Call a UDF using ADO.NET

Let’s face it, most of us typically work with Stored Procedures with modest complexity using JOINS and such. Some of us embed Common Table Expressions (CTE) in the stored procs.

If you are already using Entity Framework 2.2, you would know that stored procedures containing multiple joins is not fully supported unless it’s a SQL View in which case you would have to use DbQuery type in your DbContext class.

But, what if you have a UDF (scalar-valued function) and want to use it with ADO.NET!

Let’s see how it’s done. For the purposes of demonstration, let’s assume you have two tables: Department and Employee. Department has a one-to-many relationship with Employee, i.e. A Department can have one or more employees. This is illustrated in the Entity Relationship Diagram (ERD) below:

 

 

 

 

 

 

 

 

 

 

Next, let’s write a simple User Defined Function (UDF) which accepts @DepartmentID as an input parameter and returns the Employee Name.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION udf_GetEmployeeByID
(
	-- Add the parameters for the function here
	@DepartmentId INT
)
RETURNS NVARCHAR(50)
AS
BEGIN
	-- Declare the return variable here
	DECLARE @EmployeeName NVARCHAR(50)

	-- Add the T-SQL statements to compute the return value here
	SELECT @EmployeeName = TRIM(FirstName) + ',' + TRIM(LastName)  
	FROM 
		Employee 
	WHERE 
		DepartmentID = (SELECT DepartmentID 
						FROM Department 
						WHERE DepartmentID = @DepartmentId)

	-- Return the result of the function
	RETURN @EmployeeName

END
GO

As a quick test, let’s test this function in SQL Management Studio. We can see when the function is invoked, it returns the Employee Name which is precisely what we want.

 

 

 

 

 

 

Now, let’s open Visual Studio and create a console application and write the following method. There are a couple of things that are worth noting.

  • Since this is not a stored procedure, the command type is defined as “CommandType.Text”. If you change it to “CommandType.StoredProcedure”, the program will compile. However, it will return a null value.
  • When newing up a Sql Command object, you must use the SELECT clause when declaring the function name and passing the required parameter to it i.e. “SELECT dbo.udf_GetEmployeeByID(@DepartmentId)”
  • Don’t forget to bring in the System.Data.SqlClient namespace. You can use NuGet for this.
  • Lastly, when invoking the ExecuteScalar() command, be sure to cast it to a string (in our case).
private static string GetEmployeeNameByID(int DepID)
        {
            string retVal = string.Empty;
            using (SqlConnection connection = new SqlConnection(connStr))
            {
                try
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT dbo.udf_GetEmployeeByID(@DepartmentId)", connection))
                    {
                        connection.Open();
                        cmd.CommandType = CommandType.Text;
                        cmd.Parameters.AddWithValue("@DepartmentID", DepID);
                        retVal = (string)cmd.ExecuteScalar();
                    }
                }
                catch (SqlException ex)
                {
                    ex.Message.ToString();
                }
                return retVal;
                
            }
        }

And now let’s put the code to test, by writing it out to a console.

static void Main(string[] args)
        {

            string name = GetEmployeeNameByID(1);
            Console.WriteLine(name);
            Console.ReadLine();
        }

Output:

 

 

 

Hope, you found this segment useful!

Posted in .NET, ADO.NET, SQL Server | Leave a comment

How to Enable .NET Core 3.0 Preview in VS2019

If you are in the process of creating a Blazor app in Visual Studio 2019 that you installed right after its launch (around April 2019 timeframe), chances are you’ll find the checkbox titled “Use previews of the .NET Core SDK” in the following location:

Tools -> Options -> Projects and Solutions -> .NET Core

However, if you’ve installed Visual Studio 2019 recently (as of this writing), the option has moved to the following location:

Tools -> Options -> Environment -> Preview Features.NET Core 3 Preview

 

 

 

 

Once the above is done, close Visual Studio IDE and open it again.

Now, Create a New Project and select ASP.NET Core Web Application template and hit ‘Next’, give a project name and hit ‘Next’ again and you’ll be presented with dialog with the option to select ASP.NET Core 3.0. Make sure you also select .NET Core on the LHS. This is a requirement for the successful creation of a Blazor app. (see image below).

 

Hope you found this post useful!

Obi

Posted in .NET | Leave a comment

Migrate SQL data to Azure Cosmos DB

Azure Cosmos DB

Azure Cosmos DB is a planet scale, JSON based schema free, No SQL database with multi-API support.

Microsoft defines it as a globally distributed, multi-model database service that supports document, key-value, wide-column and graph databases.

In this column, I’ll attempt to demonstrate what a cinch it is to import SQL data into Cosmos DB. Please note, the two are not the same. The analogy to describe the two is akin to a hammer vs. an axe. Just like you cannot use a hammer to chop down a tree, similarly, you cannot use an axe to drill a nail into the wall.

What do I need:

  • SQL Server Management Studio (SSMS)
  • Azure Cosmos DB Data Migration Tool
  •  Azure Cosmos DB Emulator

Azure Cosmos DB Data Migration Tool (DTUI)

DTUI is a data migration tool that is an open source solution used to import data to Azure Cosmos DB from a variety of sources that include the following:

  1.  JSON files
  2.  Mongo DB
  3.  SQL Server
  4.  CSV files
  5.  Azure Table Storage
  6.  Dynamo DB
  7.  HBase

Azure Cosmos DB Emulator

According to Microsoft docs, the Azure Cosmos Emulator provides a high-fidelity emulation of the Azure Cosmos DB service. It supports identical functionality as Azure Cosmos DB, including support for creating and querying data, provisioning and scaling containers, and executing stored procedures and triggers. You can develop and test applications using the Azure Cosmos Emulator, and deploy them to Azure at global scale by just making a single configuration change to the connection endpoint for Azure Cosmos DB.

To download and install the Azure Cosmos Emulator, you can use this link.

Migrating Data

To migrate SQL data, we would need data. For the purposes of demonstration, I am using Adventure Works database, a Microsoft sample database that you can download here.

The Process

Let’s open SSMS and use one of the Views. A typical View is created by joining multiple related tables together. The View that is being used in this example is Purchasing.vVendorWithAddresses, where Purchasing is the name of the schema.

This View contains information about Vendor with Addresses in each row such that each of these rows can be mapped to a self-contained JSON document once the migration completes. Notice the column names that are defined as aliases. There’s also a “.” which is used as a separator to split address into address type, city, location etc. In other words, this will help shape the JSON document to transform each row into a complex JSON document instead of a flat document containing simple properties.

Although the “.” is irrelevant to SQL, however, it is used to tell the migration tool how to shape the documents that are being imported.

SELECT        
	CAST(BusinessEntityID AS VARCHAR) AS [id], 
	[Name] AS [name],
	AddressType AS [address.addressType], 
	AddressLine1 AS [address.addressLine1], 
	AddressLine2 AS [address.addressLine2], 
	City AS [address.city], 
	StateProvinceName AS [address.location.stateProvinceName], 
	PostalCode AS [address.postalCode], 
	CountryRegionName AS [address.countryRegionName]
FROM            
	Purchasing.vVendorWithAddresses

The next thing you want to do is to open the Migration Tool utility and start configuring.

Source Info

Here you will specify the API to import from, connection string, query and the nesting separator. See image below:

Target Info

Use the Azure Cosmos DB Emulator to copy the connection string (circled in red above).

One of the things you ought to keep in mind when creating a container is to define its partition key. Typically, this is a property you choose that will help scale your data both in terms of storage and throughput.

In our case, we have chosen “/address/postalCode” as the partition key.

Note: It may be noted that the name of the column defined in SQL query is case-sensitive in order for it to be recognized when transforming the query results into Cosmos DB documents.

When you click Next, you’ll be presented with an Advanced tab. Skip this section by clicking Next. 

Now you will be on the Summary page where you can review all that you have configured in the previous steps. Once you are sure, click the Import button.

The tool will import the records and transform them to documents. In this case 104 of them. See below:

 

Now, let’s flip over to Azure Cosmos DB Emulator. Refresh the page and you’ll see the newly Created Database, Collection and Documents. See below:

 

Query the Data:

With the power of SQL API that Cosmos DB supports, you can query your data just as you would if you were in SSMS. See the query below:

Output:

 

 

 

 

 

 

 

 

 

 

Summary

Here, we saw the use of SQL API and how it can be used to model data as JSON documents. We made use of a view in SQL database, massaged it and transformed the SQL records into Cosmos DB documents following some easy steps.

Resources

  1.  Azure Cosmos DB
  2. Azure Cosmos DB Data Migration Tool

 

 

Posted in NoSQL | Leave a comment

Entity Framework Core 3.0 Preview 4

Diego Vega, the Program Manager of the Entity Framework team recently announced on his blog some of the breaking changes in ASP.NET Core 3.0 Preview 4.

Some of these changes include the following:

  • LINQ queries are no longer evaluated on the client
  • EF Core runtime no longer part of the ASP.NET Core shared framework. In other words, they have to be obtained via NuGet package
  • DotNet EF Tool is no longer part of the .NET Core SDK. It has to be downloaded separately
  • Automatic key generation (reset) after in-memory database is deleted
  • Database connection no longer remains open until a TransactionScope is disposed
  • The concept of query types has been renamed to entities without keys
  • New preview of the Cosmos DB provider for EF Core.  Some of the changes include the usage of deterministic appraoch to key generation and allowing developer to specify Azure region to us. Fantastic!!!
  • EF 6.3 to target .NET Standard 2.1, in addition to already supported .NET Framework versions.

 

Posted in ORM | Leave a comment

Cannot connect to runtime process, timeout after 10000 ms

If you are a web developer, it’s given that you also write JavaScript code.

I am building an ASP.NET Core app in VS 2017 and I needed to install a feature that I chose to write in JavaScript. While everything worked fine initially, however, when I stopped the app and re-ran it, I got a nasty error. See image below:

I decided to shut down Visual Studio, launched it and open my project, but still in vain.

Turned out that in Tools => Option => Debugging => General, there is an item (circled in red) i.e. Enable JavaScript debugging for ASP.NET (Chrome, Edge and IE).

After unchecking this item and running the app, everything appeared just fine.

I certainly don’t recommend this to be a solution, but rather a workaround. Meanwhile, you can use developer tools in your favorite browser and continue debugging. Alternatively, you can also launch Visual Studio 2017 and select “Run as administrator.”

Posted in Uncategorized | Leave a comment

Query Types in EF Core

If you have been using Entity Framework 6.x or EF Core, then you are already familiar with Entities and its usage.

Query Types is a new addition to EF Core 2.1 which you can refer to Entities as its cousin.

What are some of the Use Cases

  • Is used when working with entities with no key propertie(s) defined, may it be a Table, Stored Procedure or a View
  • Is used when mapping to queries specified in the model
  • Is used for ad hoc queries where changes are not tracked in DbContext. In other words, queries that are strictly read-only

So let’s get Started

First let’s define the two POCO classes. Each of these classes below maps to the tables in the database.

public class BaseAggr
    {
        public long BaseAggrId { get; set; }
        [Display(Name = "Portfolio ID")]
        public string PortfolioId { get; set; }

        [Display(Name = "Scenario ID")]
        public long? ScenarioId { get; set; }

        [Display(Name = "Sum Pnl")]
        public double? SumPnl { get; set; }

        [Display(Name = "Business Date")]
        [DataType(DataType.Date)]
        public DateTime? BusinessDate { get; set; }
    }
    public class WhatIfAggr
    {
        public long WhatifAggrId { get; set; }

        [Display(Name="Portfolio ID")]
        public string PortfolioId { get; set; }

        [Display(Name ="Scenario ID")]
        public long? ScenarioId { get; set; }

        [Display(Name ="Sum PnL")]
        public double? SumPnl { get; set; }

        [Display(Name ="Business Date")]
        [DataType(DataType.Date)]
        public DateTime? BusinessDate { get; set; }
    }

Next, let’s create a database view. As you can tell from the query below that it’s using Common Table Expression to form a result set.

CREATE OR ALTER VIEW [dbo].[vwVarByPortfolios] AS
SELECT * FROM 
(SELECT portfolio_id, scenario_id as scenario_id, sum_pnl as var_pnl 
	FROM (SELECT portfolio_id,scenario_id, sum_pnl, RANK() OVER (PARTITION BY portfolio_id ORDER BY sum_pnl DESC) AS pnl_rank FROM base_aggr) AS Agg
	WHERE pnl_rank = 98
) AS A	INNER JOIN
	
(SELECT portfolio_id AS wi_portfolio_id, scenario_id AS wi_scenario_id, sum_pnl AS wi_var_pnl 
	FROM (SELECT portfolio_id,scenario_id, sum_pnl, RANK() OVER (PARTITION BY portfolio_id ORDER BY sum_pnl desc) AS pnl_rank from whatif_aggr) AS Agg
	WHERE pnl_rank = 98
 ) AS X
 ON portfolio_id = wi_portfolio_id;
GO

In addition to the classes above, you would also need a class for Query Type to hold results from the database view like so:

public class PortfolioView
{
public string PortfolioID { get; set; }
public long ScenarioID { get; set; }
public double VarPnl { get; set; }
public string WiPortfolioID { get; set; }
public long WiScenarioID { get; set; }
public double WiVarPnl { get; set; }
}

Next, we will create a DbQuery property in the DbContext class in order for it to be recognized as a query type.

public DbQuery PortfolioView { get; private set; }

Next, we will write a fluent API in DbConext’s OnModelCreating method to map the view to the Query Type i.e. vwVarByPortfolios. The “ToView” extension method is used to configure the mapping especially when a relational database is being targeted.

modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.PortfolioID).HasColumnName("portfolio_id");

            modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.ScenarioID).HasColumnName("scenario_id");

            modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.VarPnl).HasColumnName("var_pnl");

            modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.WiPortfolioID).HasColumnName("wi_portfolio_id");

            modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.WiScenarioID).HasColumnName("wi_scenario_id");

            modelBuilder.Query().ToView("vwVarByPortfolios")
                .Property(p => p.WiVarPnl).HasColumnName("wi_var_pnl");

Please note, DbQuery does not require a primary key to be defined unlike its DbSet<T> counterpart. The Id’s are being used here just because they are needed.

What you cannot Do:

Couple things worth noting is that in this version i.e. EF Core 2.2, EF Core does not allow Views to be created in the database when migrations are run. Conversely, you cannot reverse engineer views yet. This will most likely be available in the future version of EF Core i.e. 3.0. Here’s the EF Core Roadmap in case you wish you know further.

Lastly, you can query the database view in your console app or a Web App, although in this case, the latter is being used along with Razor Pages.

 public class PortfolioModel : PageModel
    {
        private readonly DataAggr.Models.DataAggrContext _context;

        public PortfolioModel(DataAggrContext context)
        {
            _context = context;
        }

        [BindProperty]
        public IList PortfolioView { get; set; }

        public async Task OnGetAsync()
        {
            PortfolioView = await _context.Query()
                .ToListAsync();
        }
    }

A quick snapshot of the output of the View from inside SQL Management Studio.

Output on a Razor Page in ASP.NET Core.

Hope you found the article useful!

Posted in .NET, ORM | Leave a comment