I am trying to create a dynamic way to generate report using ASP.NET MVC 5 and Entity framework in C#.
I am going to give the user a list of the available fields, ability to add filter, and ability to create a cross join from one object to another. The user decides which column and filter he/she wants to use for their custom report. Finally, I create the correct SQL query, pull the data and display it. I will need to do two main things here
- Create queries on the fly
- Build a model of the requested report on the fly
For example, I have the following two simple models
public class Customer
{
[Key]
public int Id { get; set ; }
public string FirstName { get; set ; }
public string LastName { get; set ; }
public string Phone { get; set ; }
}
public class Transaction
{
[Key]
public int Id { get; set ; }
[ForeignKey("Customer")]
public int CutomerId { get; set ; }
public decimal Amount { get; set ; }
public DateTime CreatedAt { get; set ; }
public Customer Customer { get; set; }
}
Assuming, the user wants a report that shows the customer first name, last name, phone, the sum of all their transaction and count them. The following query will give me exactly the report requirements.
SELECT c.FirstName, c.LastName, c.Phone, SUM(t.Amount) AS Amount, COUNT(*) AS total
FROM Customers AS c
INNER JOIN Transactions AS t ON t.CustomerId = c.Id
WHERE c.CreatedAt BETWEEN '2015-01-01' AND '2016-01-01'
GROUP BY c.FirstName, c.LastName, c.Phone
ORDER BY c.FirstName, c.LastName
But since this is going to be a user friendly tool I will need to be able to use either use Fluent or LINQ to generate the queries on the fly to get the data.
To convert my query to LINQ syntax, I will have to do something like this
var data = from customer in customers
join transaction in transactions on transaction.CustomerId = customer.Id
group customers by new { customer.FirstName, customer.LastName, customer.Phone } into g
order by customer.FirstName, customer.LastName
select new {
FirstName = g.FirstName,
LastName = g.LastName,
Phone = g.Phone,
Amount = g.Sum(s => s.Amount)
Total = g.Count()
}
Is there a way to know the relation between models using Entity framework and the keys so I can use to join the tables? Also, is there a way to get the available attributes
for each object from Entity so I can list the fields for the user?
Also, how can I create a model on the fly where I can pass it to a view for display?