Wednesday, 3 August 2016

sql server - Entity Framework - Saving entity generates an Id but record isn't added to database

I'm trying to insert a new record using Entity Framework using the following code. Within the BuildRequest.Save() method in the BuildRequest class, when the 'Insert' occurs, and the db.Save() is done, a JobId is correctly generated for the BuildRequest (indicating that the Insert is being done correctly), however the record isn't added to the database.




When I check in SQL profiler, here's what the insert is trying to do:



exec sp_executesql N'INSERT [dbo].[BuildQueue]([ApplicationId], [BuildReason])
VALUES (@0, @1)

SELECT [JobId]
FROM [dbo].[BuildQueue]
WHERE @@ROWCOUNT > 0 AND [JobId] = scope_identity()',N'@0 int,@1 tinyint,@0=5819,@1=0



Here is my call to create a new 'job':



BuildRequest job = new BuildRequest(ApplicationId, Core.BuildReasons.NewApp);
job.Save()


which uses the following class:



public class BuildRequest
{

private Data.BuildQueue _buildRequest;

public BuildRequest(int applicationId, BuildReasons reason)
{
_buildRequest = new Data.BuildQueue();
ApplicationId = applicationId;
BuildReason = reason;
}

public int JobId

{
get { return _buildRequest.JobId; }
}

public int ApplicationId
{
get
{
return _buildRequest.ApplicationId;
}

set
{
_buildRequest.ApplicationId = value;
}
}

public BuildReasons BuildReason
{
get
{

return (BuildReasons)_buildRequest.BuildReason;
}
set
{
_buildRequest.BuildReason = (byte)value;
}
}

public int Save()
{

using (Core.Data.UnitOfWork db = new Data.UnitOfWork())
{
Data.BuildQueue buildRequest = db.BuildQueueRepository.Get(a => a.JobId == this.JobId).SingleOrDefault();
if (buildRequest == null)//current build request doesn't already exist
{
db.BuildQueueRepository.Insert(_buildRequest);
}
else // we're editing an existing build request
{
db.BuildQueueRepository.Update(_buildRequest);

}

db.Save();
// **At this point, _buildRequest has a JobId, but no record is added to the database
return JobId;
}
}
}



What I've checked so far:




  • the 'UnitOfWork' object I create ('db'), is connected to the correct database (a remote SQL server database)

  • the db.BuildQueueRepository.Insert(...) is correctly calling dbSet.Add(entity);

  • the db.Save() is correctly calling context.SaveChanges();

  • there's existing code elsewhere in my application that uses the same generic UnitOfWork repository, which appears almost identical to the code above, and it works perfectly



What could be happening? What could be the difference in the code that's working correctly?

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...