I've done a lot of Googling re this subject, but can't seem to find any clear answer that works. This maybe because of the way the different EF versions has worked (or not) in the past.
I'm currently using Asp.Net 4.0 with EF 6.1. My model is database first. Additionally, I'm using my own UOW, repository pattern but this is just for information.
Firstly, the reason I want to call a stored procedure is because I need to incorporate a 'counter' into my table - put simply each time anyone visits a particular partner, I need to increment the counter. Of course, the main issue using EF is concurrency.
The articles I've read, tell me that EF isn't good at this type of update, however if this is now deemed easier to achieve in later EF versions, I'd be interested to hear more. Otherwise, I'm left with a native stored procedure - 2 options I guess
- call from EF, and
- call directly
Since I've been using primarily EF, my knowledge of SQL is fairly sparse, but I've created the following stored procedure:
ALTER PROCEDURE dbo.Popularity_Update
@TermID smallint
AS
SET NOCOUNT ON
DECLARE @Now date = SYSDATETIME()
BEGIN TRY
MERGE Popularity AS t
USING (SELECT @TermID AS TermID, @Now AS VisitDate) AS s ON t.TermID = s.TermID
AND t.VisitDate = s.VisitDate
WHEN MATCHED THEN
UPDATE
SET VisitCount += 1
WHEN NOT MATCHED BY TARGET THEN
INSERT (TermID, VisitDate, VisitCount)
VALUES (s.TermID, s.VisitDate, 1);
END TRY
BEGIN CATCH
END CATCH
That's were I get lost. I noticed within the EF designer that the stored procedure could be referenced, so I added the table to my model and then mapped the stored procedure.
But I also noticed that I can reference a stored procedure from code using the following code:
var name = new SqlParameter("TermID", typeof(short));
uow.Context.Database.ExecuteSqlCommand("Popularity_Update", name);
At the moment, I'm just confused and have lots of questions.
- Can this be done in EF without a stored procedure?
- Should it be done in EF without a stored procedure?
- If I use a stored procedure - whats the best way to do this?
I'd appreciate any help/guidance available.