Carl
Carl

Reputation: 1832

FromSqlInterpolated 'hydrating' wrong data

Edit: answered below

This is an odd one that I've been looking at all day. I'm calling this function:

.FromSqlInterpolated($"""
                      SELECT Username, UserId, Year, Month, OrganizationId, Day, Min(Id) as Id, {startDate} as LoggedOn, {startDate} as LoggedOff, cast (0 as bigint) [timeloggedin]
                      FROM UserActivities U
                      WHERE DATEFROMPARTS(Year, Month, Day) >= {startDate}
                      GROUP BY OrganizationId, Year, Month, Day, UserName, UserId
                      """)
.ToListAsync()

Here's the entity:

public class UserActivity
{
    public long Id { get; set; }
    public string UserId { get; set; } = string.Empty;
    public string Username { get; set; } = string.Empty;
    public long OrganizationId { get; set; }
    public int Year { get; set; }
    public int Month { get; set; }
    public int Day { get; set; }
    public Instant LoggedOn { get; set; }
    public Instant LoggedOff { get; set; }
    public Duration TimeLoggedIn { get; set; }
}

Here's the configuration:

public void Configure(EntityTypeBuilder<UserActivity> builder)
{
    builder.Property(x => x.TimeLoggedIn).HasConversion(new DurationValueConverter());
}

Now.. I call this, and I'm getting some errors in the data. They are exactly the same every time.

Here's a sample from the database, including the query that I used:

SELECT 'redacted' [Username], UserId, Year, Month, OrganizationId, Day, 
    Min(Id) as Id, '2024-12-01' as LoggedOn, 
    '2024-12-01' as LoggedOff, cast (0 as bigint) [timeloggedin]
FROM UserActivities
WHERE UserId = 'ede6cc89-aceb-4683-a737-0bb81b569530'
AND DATEFROMPARTS(Year, Month, Day) >= '2024-12-01'
GROUP BY OrganizationId, Year, Month, Day, UserName, UserId
ORDER BY Year, Month, Day

enter image description here

And here is a snip from the results of the C# query from above (filtered to the User Id and sorted):

enter image description here

The first records for each month have had the 'Day' value replaced with a 0 There are the same number of records in both the database results and the C# list, and each record has a unique id.

Where do the 0s come from? And how do I stop it?

Using .Net 7 and EF-Core 7.0.7

Upvotes: 0

Views: 24

Answers (1)

Carl
Carl

Reputation: 1832

Found it as I posted this question. I had earlier used similar entities and they were being tracked. Loading this with no tracking made everything work.

Upvotes: 0

Related Questions