I have a true code-first deployment of my data model and I have a need to perform functionality one would normally associate to a view, but I'm not sure how to accomplish it at the moment.
To simplify the problem, my model has things a registered user creates and posts that other users can interact with. I'm devising an algorithm for how popular these things are that boils down to a weighting factor related to the type of interaction times the inverse of some date period.
As an example let's say we have "Likes", "Comments", and "Purchases" with weights of 1, 2, and 3 respectively. Let's also say my time period is 1 week. In that scenario a purchase 3 weeks ago weighs as much as a Like in the current week.
So the relevant parts of the model are the Thing
which has a Primary Key and some additional metadata; the InteractionType
which has a Primary Key, a Weight
value, and some other metadata; the Interaction
which has a composite Primary Key (consisting of the Thing
Primary Key, User
object Primary Key, and InteractionType
Primary Key) and a DateValue
column and any other contextually related metadata.
Ultimately I want to have an entity framework compatible way to perform the following query:
;WITH InteractionScore
AS
(
SELECT t.Id ThingId, SUM(it.Weight/CAST(DATEDIFF(wk, i.DateValue, GETDATE()) AS float)) IntScore
FROM Things t
INNER JOIN Interactions i ON t.Id = i.ThingId
INNER JOIN InteractionTypes it ON i.InteractionTypeId = it.Id
GROUP BY t.ID
)
SELECT TOP(10) t.*
FROM Things t
LEFT JOIN InteractionScore isc ON t.Id = isc.ThingId
ORDER BY ISNULL(isc.IntScore, 0.0) DESC
Data Model Classes are defined as follows:
namespace Project.Entities
{
public class User
{
[Key]
public int Id {get; set;}
public string IdentityRef {get;set;}
public string DisplayName {get;set;}
[InverseProperty("Owner")]
public ICollection<Thing> OwnedThings {get; set;}
}
public class InteractionType
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public double Weight { get; set; }
}
public class Thing
{
[Key]
public int Id {get;set;}
public int OwnerId {get; set;}
[ForeignKey("OwnerId")]
public User Owner {get; set;}
public string Summary {get; set;}
public string Description {get; set;}
public ICollection<Interaction> Interactions {get;set;}
}
public class Interaction
{
public int ThingId { get; set; }
public int UserId { get; set; }
public int InteractionTypeId {get; set;}
public Thing Thing {get; set;}
public User User {get;set;}
public InteractionType InteractionType {get;set;}
public DateTime DateValue {get;set;}
public string Comment {get; set;}
public string PurchaseReference {get;set;}
}
}
The DbContext definition in the consuming application
namespace Project.Consumer
{
public class ApplicationData : DbContext
{
public DbSet<User> Users {get;set;}
public DbSet<Thing> Things {get;set;}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
builder.Entity<Interaction>()
.HasKey(i => new {i.ThingId, i.UserId, i.InteractionTypeId});
}
}
public List<Thing> GetMostPopularThings(ApplicationData ctx)
{
return ctx.Things.OrderByDescending(lambdaMagic).Take(10).ToList();
}
}
The lambdaMagic is snark of course, but as I said, I'm not sure if there is a documented way of doing this and I'm just missing it or what. I've seen the option to do something along the lines of ctx.Things.FromSql("select string or sp here").Take(10).ToList();
and that might be okay, but I really wanted to reduce the number of things that exist outside the project (SP definitions for example)
Since writing this question, I went ahead and created another model class called ThingStatistics:
public class ThingStatistics
{
[Key]
public int ThingId {get; set;}
[ForeignKey("ThingId")]
public Thing Thing {get; set;}
public double InteractionScore {get;set;}
}
Then I augmented the Thing class as follows:
public class Thing
{
[Key]
public int Id {get;set;}
public int OwnerId {get; set;}
[ForeignKey("OwnerId")]
public User Owner {get; set;}
public string Summary {get; set;}
public string Description {get; set;}
public ICollection<Interaction> Interactions {get;set;}
public ThingStatistics Stats {get;set;}
}
I performed the Add-Migration step and then altered the resulting Up/Down as follows:
public partial class AggregationHack : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("GO; CREATE VIEW ThingStatistics AS SELECT t.ID ThingId, ISNULL(it.Weight/CAST(DATEDIFF(wk, i.DateValue, GETDATE()) + 1 AS float), 0) InteractionScore FROM Things t LEFT JOIN Interactions i INNER JOIN InteractionTypes it ON i.InteractionTypeId = it.Id ON t.ID = i.ThingId GROUP BY t.Id; GO;");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.Sql("DROP VIEW ThingStatistics; GO;");
}
}
So, now I can do ctx.Things.Include(t => t.Stats).OrderByDescending(t => t.Stats.InteractionScore).Take(10).ToList()
and that works, but I don't know if that is correct because it feels like such a hack...