0

I'm trying to create an object by manually inserting the primary key, but it's not possible the way I have it. I tried to put the ExecuteSqlCommand() but it doesn't exist.

I check this https://stackoverflow.com/a/43973327/13954475 but that didn't solve my problem.

I have this:

public void CreateYear(int yearId)
{
        try 
        {
            Year year = new Year();
            year.YearId = yearId;
            year.YearAcademic = yearId.ToString() + "/" + (yearId + 1).ToString();
            year.IsActive = false;

            _context.Database.ExecuteSql($"SET IDENTITY_INSERT dbo.Years ON");
            _context.Years.Add(year);
            _context.SaveChanges();
            _context.Database.ExecuteSql($"SET IDENTITY_INSERT dbo.Years OFF");

        }
        catch
        {
            throw;
        }
            
}

I also tried with ExecuteSqlRaw and others.

  • 1
    Best solution : **do not** try to insert the identity value - let the database handle that for you (that's what it's intended for, really) – marc_s Nov 25 '22 at 10:51
  • Yes, but I wanted a unique value for each year. Maybe add then a field with unique value instead of using Id, right? – Bruno Silva Nov 25 '22 at 11:01
  • 3
    The `IDENTITY` column handled by the database will do this - you don't need to do anything at all ! – marc_s Nov 25 '22 at 11:24
  • 1
    The answer you refer to *does* solve your problem. You just didn't do everything that's in it. That said, I agree with marc_s: don't do this. Don't use an identity column in the first place here. – Gert Arnold Nov 25 '22 at 12:41
  • Update: The answer I referred to earlier solved my problem, however, I also found the intended solution to the initial question. I used the method `ExecuteSqlInterpolated()` instead. And remove `dbo.`. – Bruno Silva Nov 26 '22 at 21:12
  • PS: I have added `_context.Database.OpenConnection();` before try{ }. it workes for me – Bruno Silva Dec 02 '22 at 19:58

0 Answers0