Reputation: 9900
Just wondering what the best (fastest execution time) method for translating the following SQL to LINQ to SQL is?
IF EXISTS (SELECT TOP 1 * FROM HealthIndicators WHERE LogDate = getdate())
UPDATE HealthIndicators SET Timeouts = 32
ELSE INSERT INTO HealthIndicators (Timeouts, 32)
I apologise if this is a repost but I haven't been able to find an answer on the subject (I'm new, please be nice!)
Upvotes: 3
Views: 179
Reputation: 100268
var d = DateTime.Today; // or .Now
if (db.HealthIndicators.FirstOrDefault(h => h.LogDate == d) != null)
// or Any(h => h.LogDate == d)
{
// update
}
else
{
// insert
}
Upvotes: 2
Reputation: 194
I would just add one more item to the answer above. The answer above uses a DateTime.Today which uses the time from the machine the code is running on instead of getdate() which grabs the time from Sql Server. This can matter if your application has a separate database server. To do this you have to add the following function to your ORM.
[Function(Name="GetDate", IsComposable=true)]
public DateTime GetSystemDate()
{
MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo;
return (DateTime)this.ExecuteMethodCall(this, mi, new object[]{}).ReturnValue;
}
Upvotes: 1