Using Entity Framework datasources (VB.Net / netframework)
Note
This demo is available in your FlexCel installation at <FlexCel Install Folder>\samples\vb\VS2022\netframework\20.Reports\24.Entity Framework Reports and also at https://github.com/tmssoftware/TMS-FlexCel.NET-demos/tree/master/vb/VS2022/netframework/Modules/20.Reports/24.Entity Framework Reports
Overview
Note
To run this example, you need to have SQL Server (LocalDB) installed. For this reason, and because it uses NuGet, this demo doesn't run from MainDemo. You need to open this solution and run it alone.
While you can use any generic IQueryable<T> object as a source of reports, here we provide a concrete example of redoing the "range reports" demo using Entity Framework.
Concepts
Entity Framework reports should be run inside a serializable or snapshot transaction. While snapshot transactions are preferred as they won't block other users from changing the data while the report is running, in this example we use serializable (Because LocalDB doesn't support snapshot)
Here we have an implicit relationship between categories and products, so we don't need to add an explicit one. The report will just work.
Files
AssemblyInfo.vb
Imports System.Reflection
Imports System.Runtime.CompilerServices
'
' General Information about an assembly is controlled through the following
' set of attributes. Change these attribute values to modify the information
' associated with an assembly.
'
<Assembly: AssemblyTitle("")>
<Assembly: AssemblyDescription("")>
<Assembly: AssemblyConfiguration("")>
<Assembly: AssemblyCompany("")>
<Assembly: AssemblyProduct("")>
<Assembly: AssemblyCopyright("")>
<Assembly: AssemblyTrademark("")>
<Assembly: AssemblyCulture("")>
'
' Version information for an assembly consists of the following four values:
'
' Major Version
' Minor Version
' Build Number
' Revision
'
' You can specify all the values or you can default the Revision and Build Numbers
' by using the '*' as shown below:
<Assembly: AssemblyVersion("1.0.*")>
'
' In order to sign your assembly you must specify a key to use. Refer to the
' Microsoft .NET Framework documentation for more information on assembly signing.
'
' Use the attributes below to control which key is used for signing.
'
' Notes:
' (*) If no key is specified, the assembly is not signed.
' (*) KeyName refers to a key that has been installed in the Crypto Service
' Provider (CSP) on your machine. KeyFile refers to a file which contains
' a key.
' (*) If the KeyFile and the KeyName values are both specified, the
' following processing occurs:
' (1) If the KeyName can be found in the CSP, that key is used.
' (2) If the KeyName does not exist and the KeyFile does exist, the key
' in the KeyFile is installed into the CSP and used.
' (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
' When specifying the KeyFile, the location of the KeyFile should be
' relative to the project output directory which is
' %Project Directory%\obj\<configuration>. For example, if your KeyFile is
' located in the project directory, you would specify the AssemblyKeyFile
' attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
' (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
' documentation for more information on this.
'
<Assembly: AssemblyDelaySign(False)>
<Assembly: AssemblyKeyFile("")>
<Assembly: AssemblyKeyName("")>
Category.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class Category
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")> _
Public Sub New()
Me.Products = New HashSet(Of Product)()
End Sub
Public Property CategoryID() As Integer
Public Property CategoryName() As String
Public Property Description() As String
Public Property Picture() As Byte()
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Products() As ICollection(Of Product)
End Class
End Namespace
Customer.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class Customer
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")> _
Public Sub New()
Me.Orders = New HashSet(Of Order)()
Me.CustomerDemographics = New HashSet(Of CustomerDemographic)()
End Sub
Public Property CustomerID() As String
Public Property CompanyName() As String
Public Property ContactName() As String
Public Property ContactTitle() As String
Public Property Address() As String
Public Property City() As String
Public Property Region() As String
Public Property PostalCode() As String
Public Property Country() As String
Public Property Phone() As String
Public Property Fax() As String
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Orders() As ICollection(Of Order)
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property CustomerDemographics() As ICollection(Of CustomerDemographic)
End Class
End Namespace
CustomerDemographic.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class CustomerDemographic
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")> _
Public Sub New()
Me.Customers = New HashSet(Of Customer)()
End Sub
Public Property CustomerTypeID() As String
Public Property CustomerDesc() As String
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Customers() As ICollection(Of Customer)
End Class
End Namespace
Employee.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class Employee
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")> _
Public Sub New()
Me.Employees1 = New HashSet(Of Employee)()
Me.Orders = New HashSet(Of Order)()
Me.Territories = New HashSet(Of Territory)()
End Sub
Public Property EmployeeID() As Integer
Public Property LastName() As String
Public Property FirstName() As String
Public Property Title() As String
Public Property TitleOfCourtesy() As String
Public Property BirthDate() As Date?
Public Property HireDate() As Date?
Public Property Address() As String
Public Property City() As String
Public Property Region() As String
Public Property PostalCode() As String
Public Property Country() As String
Public Property HomePhone() As String
Public Property Extension() As String
Public Property Photo() As Byte()
Public Property Notes() As String
Public Property ReportsTo() As Integer?
Public Property PhotoPath() As String
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Employees1() As ICollection(Of Employee)
Public Overridable Property Employee1() As Employee
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Orders() As ICollection(Of Order)
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Territories() As ICollection(Of Territory)
End Class
End Namespace
Form1.Designer.vb
Imports System.Collections
Imports System.ComponentModel
Imports System.IO
Imports System.Reflection
Imports FlexCel.Core
Imports FlexCel.XlsAdapter
Imports FlexCel.Report
Namespace EntityFrameworkReports
Partial Public Class mainForm
Inherits System.Windows.Forms.Form
Private WithEvents button1 As System.Windows.Forms.Button
Private saveFileDialog1 As System.Windows.Forms.SaveFileDialog
Private label1 As System.Windows.Forms.Label
Private WithEvents btnCancel As System.Windows.Forms.Button
''' <summary>
''' Required designer variable.
''' </summary>
Private components As System.ComponentModel.Container = Nothing
''' <summary>
''' Clean up any resources being used.
''' </summary>
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If components IsNot Nothing Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
#Region "Windows Form Designer generated code"
''' <summary>
''' Required method for Designer support - do not modify
''' the contents of this method with the code editor.
''' </summary>
Private Sub InitializeComponent()
Me.button1 = New System.Windows.Forms.Button()
Me.saveFileDialog1 = New System.Windows.Forms.SaveFileDialog()
Me.label1 = New System.Windows.Forms.Label()
Me.btnCancel = New System.Windows.Forms.Button()
Me.SuspendLayout()
'
' button1
'
Me.button1.Anchor = (CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
Me.button1.BackColor = System.Drawing.Color.Green
Me.button1.ForeColor = System.Drawing.Color.White
Me.button1.Location = New System.Drawing.Point(152, 88)
Me.button1.Name = "button1"
Me.button1.Size = New System.Drawing.Size(112, 23)
Me.button1.TabIndex = 0
Me.button1.Text = "GO!"
Me.button1.UseVisualStyleBackColor = False
' Me.button1.Click += New System.EventHandler(Me.button1_Click)
'
' saveFileDialog1
'
Me.saveFileDialog1.Filter = "Excel Files|*.xls"
Me.saveFileDialog1.RestoreDirectory = True
'
' label1
'
Me.label1.Location = New System.Drawing.Point(24, 24)
Me.label1.Name = "label1"
Me.label1.Size = New System.Drawing.Size(272, 24)
Me.label1.TabIndex = 2
Me.label1.Text = "Press ""GO"" to create a database Report."
'
' btnCancel
'
Me.btnCancel.Anchor = (CType((System.Windows.Forms.AnchorStyles.Top Or System.Windows.Forms.AnchorStyles.Right), System.Windows.Forms.AnchorStyles))
Me.btnCancel.BackColor = System.Drawing.Color.FromArgb((CInt((CByte(192)))), (CInt((CByte(0)))), (CInt((CByte(0)))))
Me.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel
Me.btnCancel.ForeColor = System.Drawing.Color.White
Me.btnCancel.Location = New System.Drawing.Point(272, 88)
Me.btnCancel.Name = "btnCancel"
Me.btnCancel.Size = New System.Drawing.Size(112, 23)
Me.btnCancel.TabIndex = 3
Me.btnCancel.Text = "Cancel"
Me.btnCancel.UseVisualStyleBackColor = False
' Me.btnCancel.Click += New System.EventHandler(Me.btnCancel_Click)
'
' mainForm
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6F, 13F)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(416, 133)
Me.Controls.Add(Me.btnCancel)
Me.Controls.Add(Me.label1)
Me.Controls.Add(Me.button1)
Me.Name = "mainForm"
Me.Text = "Entity Framework Reports"
Me.ResumeLayout(False)
End Sub
#End Region
End Class
End Namespace
Form1.vb
Imports System.Collections
Imports System.ComponentModel
Imports System.IO
Imports System.Reflection
Imports FlexCel.Core
Imports FlexCel.XlsAdapter
Imports FlexCel.Report
Imports System.Transactions
Imports System.Configuration
Namespace EntityFrameworkReports
''' <summary>
''' Summary description for Form1.
''' </summary>
Partial Public Class mainForm
Inherits System.Windows.Forms.Form
Public Sub New()
InitializeComponent()
End Sub
Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles button1.Click
AutoRun()
End Sub
Public Sub AutoRun()
Using ordersReport As New FlexCelReport(True)
Dim DataPath As String = Path.Combine(Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), ".."), "..") & Path.DirectorySeparatorChar
ordersReport.SetValue("Date", Date.Now)
Using Northwind As New northwndEntities()
ordersReport.AddTable("Categories", Northwind.Categories)
ordersReport.AddTable("Products", Northwind.Products)
If saveFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Dim transactionOptions As New TransactionOptions()
transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.Serializable 'it would be better to sue Snapshot here, but it isn't supported by SQL Sever CE
Using transactionScope As New TransactionScope(TransactionScopeOption.Required, transactionOptions)
ordersReport.Run(DataPath & "Entity Framework Reports.template.xls", saveFileDialog1.FileName)
transactionScope.Complete()
End Using
If MessageBox.Show("Do you want to open the generated file?", "Confirm", MessageBoxButtons.YesNo) = System.Windows.Forms.DialogResult.Yes Then
Process.Start(saveFileDialog1.FileName)
End If
End If
End Using
End Using
End Sub
Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Close()
End Sub
End Class
End Namespace
ModelNorthwind.Context.vb
Imports System.Data.Entity.Infrastructure
Imports System.Data.Entity
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class northwndEntities
Inherits DbContext
Public Sub New()
MyBase.New("name=northwndEntities")
End Sub
Protected Overrides Sub OnModelCreating(ByVal modelBuilder As DbModelBuilder)
Throw New UnintentionalCodeFirstException()
End Sub
Public Overridable Property Categories() As DbSet(Of Category)
Public Overridable Property CustomerDemographics() As DbSet(Of CustomerDemographic)
Public Overridable Property Customers() As DbSet(Of Customer)
Public Overridable Property Employees() As DbSet(Of Employee)
Public Overridable Property Order_Details() As DbSet(Of Order_Detail)
Public Overridable Property Orders() As DbSet(Of Order)
Public Overridable Property Products() As DbSet(Of Product)
Public Overridable Property Regions() As DbSet(Of Region)
Public Overridable Property Shippers() As DbSet(Of Shipper)
Public Overridable Property Suppliers() As DbSet(Of Supplier)
Public Overridable Property Territories() As DbSet(Of Territory)
End Class
End Namespace
ModelNorthwind.Designer.vb
' T4 code generation is enabled for model ''.
' To enable legacy code generation, change the value of the 'Code Generation Strategy' designer
' property to 'Legacy ObjectContext'. This property is available in the Properties Window when the model
' is open in the designer.
' If no context and entity classes have been generated, it may be because you created an empty model but
' have not yet chosen which version of Entity Framework to use. To generate a context class and entity
' classes for your model, open the model in the designer, right-click on the designer surface, and
' select 'Update Model from Database...', 'Generate Database from Model...', or 'Add Code Generation
' Item...'.
ModelNorthwind.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Order.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class Order
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")> _
Public Sub New()
Me.Order_Details = New HashSet(Of Order_Detail)()
End Sub
Public Property OrderID() As Integer
Public Property CustomerID() As String
Public Property EmployeeID() As Integer?
Public Property OrderDate() As Date?
Public Property RequiredDate() As Date?
Public Property ShippedDate() As Date?
Public Property ShipVia() As Integer?
Public Property Freight() As Decimal?
Public Property ShipName() As String
Public Property ShipAddress() As String
Public Property ShipCity() As String
Public Property ShipRegion() As String
Public Property ShipPostalCode() As String
Public Property ShipCountry() As String
Public Overridable Property Customer() As Customer
Public Overridable Property Employee() As Employee
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Order_Details() As ICollection(Of Order_Detail)
Public Overridable Property Shipper() As Shipper
End Class
End Namespace
Order_Detail.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class Order_Detail
Public Property OrderID() As Integer
Public Property ProductID() As Integer
Public Property UnitPrice() As Decimal
Public Property Quantity() As Short
Public Property Discount() As Single
Public Overridable Property Order() As Order
Public Overridable Property Product() As Product
End Class
End Namespace
Product.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class Product
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")> _
Public Sub New()
Me.Order_Details = New HashSet(Of Order_Detail)()
End Sub
Public Property ProductID() As Integer
Public Property ProductName() As String
Public Property SupplierID() As Integer?
Public Property CategoryID() As Integer?
Public Property QuantityPerUnit() As String
Public Property UnitPrice() As Decimal?
Public Property UnitsInStock() As Short?
Public Property UnitsOnOrder() As Short?
Public Property ReorderLevel() As Short?
Public Property Discontinued() As Boolean
Public Overridable Property Category() As Category
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Order_Details() As ICollection(Of Order_Detail)
Public Overridable Property Supplier() As Supplier
End Class
End Namespace
Program.vb
Namespace EntityFrameworkReports
Friend NotInheritable Class Program
Private Sub New()
End Sub
''' <summary>
''' The main entry point for the application.
''' </summary>
<STAThread> _
Shared Sub Main()
Application.EnableVisualStyles()
Application.SetCompatibleTextRenderingDefault(False)
Application.Run(New mainForm())
End Sub
End Class
End Namespace
Region.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class Region
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")> _
Public Sub New()
Me.Territories = New HashSet(Of Territory)()
End Sub
Public Property RegionID() As Integer
Public Property RegionDescription() As String
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Territories() As ICollection(Of Territory)
End Class
End Namespace
Shipper.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class Shipper
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")> _
Public Sub New()
Me.Orders = New HashSet(Of Order)()
End Sub
Public Property ShipperID() As Integer
Public Property CompanyName() As String
Public Property Phone() As String
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Orders() As ICollection(Of Order)
End Class
End Namespace
Supplier.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class Supplier
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")> _
Public Sub New()
Me.Products = New HashSet(Of Product)()
End Sub
Public Property SupplierID() As Integer
Public Property CompanyName() As String
Public Property ContactName() As String
Public Property ContactTitle() As String
Public Property Address() As String
Public Property City() As String
Public Property Region() As String
Public Property PostalCode() As String
Public Property Country() As String
Public Property Phone() As String
Public Property Fax() As String
Public Property HomePage() As String
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Products() As ICollection(Of Product)
End Class
End Namespace
Territory.vb
'------------------------------------------------------------------------------
' <auto-generated>
' This code was generated from a template.
'
' Manual changes to this file may cause unexpected behavior in your application.
' Manual changes to this file will be overwritten if the code is regenerated.
' </auto-generated>
'------------------------------------------------------------------------------
Namespace EntityFrameworkReports
Partial Public Class Territory
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")> _
Public Sub New()
Me.Employees = New HashSet(Of Employee)()
End Sub
Public Property TerritoryID() As String
Public Property TerritoryDescription() As String
Public Property RegionID() As Integer
Public Overridable Property Region() As Region
<System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")> _
Public Overridable Property Employees() As ICollection(Of Employee)
End Class
End Namespace