Is EF doind something crazy? - sql

We have this EF 6 code,
var existingProduct = _productContext.Product.FirstOrDefault(
s => s.Name.ToUpper().Trim() == productDto.Name.ToUpper().Trim()
&& s.IDReference == productDto.IDReference);
if (existingProduct != null)
{
return existingProduct;
}
_productContext.Product.Add(productDto);
_productContext.SaveChanges();
return productDto;
It works sometimes and doesn't other times, it times out and we get this error,
An error occurred while updating the entries. See the inner exception
for details. An error occurred while updating the entries. See the
inner exception for details. Execution Timeout Expired. The timeout
period elapsed prior to completion of the operation or the server is
not responding. The statement has been terminated. The wait operation
timed out
Am I doing anything wrong ? Is it locking anything ?
It shows that its blocking something as below,
https://prnt.sc/re7h0w

Related

Database timeout in Azure SQL

We have a .Net Core API accessing Azure SQL (Gen5, 4 vCores)
Since quite some time,
the API keeps throwing below exception for a specific READ operation
Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout
Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
The READ operation has code to read rows of data and convert an XML column into a specific output format.
Most of the read operation extracts hardly 4-5 rows # a time.
The tables involved in the query have ~ 500,000 rows
We are clueless on Root Cause of this issue.
Any hints on where to start looking # for root cause?
Any pointer would be highly appreciated.
NOTE : Connection string has following settings, apart from others
MultipleActiveResultSets=True;Connection Timeout=60
Overall code looks something like this.
HINT: The above timeout exception comes # ConvertHistory, when the 2nd table is being read.
HttpGet]
public async Task<IEnumerable<SalesOrders>> GetNewSalesOrders()
{
var SalesOrders = await _db.SalesOrders.Where(o => o.IsImported == false).OrderBy(o => o.ID).ToListAsync();
var orders = new List<SalesOrder>();
foreach (var so in SalesOrders)
{
var order = ConvertSalesOrder(so);
orders.Add(order);
}
return orders;
}
private SalesOrder ConvertSalesOrder(SalesOrder o)
{
var newOrder = new SalesOrder();
var oXml = o.XMLContent.LoadFromXMLString<SalesOrder>();
...
newOrder.BusinessUnit = oXml.BusinessUnit;
var history = ConvertHistory(o.ID);
newOrder.history = history;
return newOrder;
}
private SalesOrderHistory[] ConvertHistory(string id)
{
var history = _db.OrderHistory.Where(o => o.ID == id);
...
}
Microsoft.Data.SqlClient.SqlException (0x80131904): Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
From Microsoft Document,
You will get this error in both conditions Connection timeout or Query or command timeout. first identify it from call stack of the error messages.
If you found it as a connection issue you can either Increase connection timeout parameter. if you are still getting same error, it is causing due to a network issue.
from information that you provided It is Query or command timeout error to work around this error you can set CommandTimeout for query or command
command.CommandTimeout = 10;
The default timeout value is 30 seconds, the query will continue to run until it is finished if the time-out value is set to 0 (no time limit).
For more information refer Troubleshoot query time-out errors provided by Microsoft.

Issue raising an error in after trigger

I'm having an issue raising an error in an after trigger, and I don't see any reason why I can raise an error one way, but not the other. Let me give you an example.
The following trigger will fail and raise the following error:
Error:Apex trigger tstTrigger2 caused an unexpected exception, contact
your administrator: tstTrigger2 : execution of AfterUpdate caused by:
System.FinalException: SObject row does not allow errors:
Trigger.tstTrigger2 : line 19, column 1
trigger tstTrigger2 on Account (after update)
{
Set<Id> AccountIds = Trigger.newMap.keySet();
List<Account > accountsToProcess = [Select Id, Name from Account Where Id IN : AccountIds];
for(Account act: accountsToProcess)
{
act.addError('doesn't work');
}
}
However, raising an error this way works. Please note there is always ever only 1 record in the keyset, at least in this test scenario.
trigger tstTrigger on Account (after update)
{
Set<Id> AccountIds = Trigger.newMap.keySet();
List<Account > accountsToProcess = [Select Id, Name from Account Where Id IN : AccountIds];
Trigger.new[0].addError('However, this works?');
}
Any explanation of why the first one is failing, and the second one is not is greatly appreciated. As well, if you could point me to the best way to implement this so that it's bulkified that would be great. Thanks!
addError() doesn't roll back your insertion it will just prevent the further execution of the script, so the data is never inserted if an you throw an error on UI.
By doing this
Trigger.new[0].addError('However, this works?');
You're simply throwing an error on the first record in the list thereby stopping anything processing.
Something like this will solve your first code snip
trigger tstTrigger2 on Account (after update)
{
Map<ID, Account> accountMap = Trigger.newMap;
for(ID act: accountMap.keySet())
{
accountMap.get(act).addError('doesnt work');
}
}
You were querying out the account Ids and by that time they were already committed to the database, which won't allow errors to be flagged on the records

Doctrine deadlock with ORM updates

I'm trying to figure out what is causing deadlocks in my Symfony 2 application. I'm running a cronjob that does batch-updates on a fairly large dataset and one part of it causes this error:
Doctrine\DBAL\DBALException: An exception occurred while executing
'UPDATE SpotEvent SET ts = ?, current = ? WHERE id = ?' with params
["2015-12-28 00:35:27", 1, 39316]: SQLSTATE[40P01]: Deadlock
detected: 7 ERROR: deadlock detected DETAIL: Process 32030 waits for
ShareLock on transaction 2130787; blocked by process 32029. Process
32029 waits for ShareLock on transaction 2130786; blocked by process
32030. HINT: See server log for query details. CONTEXT: while updating tuple (105,68) in relation "spotevent" (uncaught exception)
at
/home/maf/symfony/vendor/doctrine/dbal/lib/Doctrine/DBAL/DBALException.php
line 91 while running console command
The code causing it is basically this:
check event
if (already in database) {
update timestamp
} else {
create new
}
From what I see in the error, the first branch causes the deadlock, but from what I read about deadlocks, the second should be more likely. In any case I don't understand why I have a deadlock at all.
I should say I am running this job in 6 parallel processes. However, there is no overlap between them (i.e. job one is checking from 1-200, job 2 from 201 to 400, etc.)
I'm using PostgreSQL as the database backend. My "check event" step is done using DQL, everything else is pure ORM.

time out error using entity framework?

We have the following code:
var db = new CoreEntityDB();
var abc = new abcDB();
var connection = new DataStore(db.ConnectionStrings.First(p => p.Name == "Abc").Value, DataStore.Server.SqlServer);
var projects = new List<abc_Employees>();
projects.AddRange(abc.Database.SqlQuery<abc_Employees>("usp_ABC_EmployeeSys"));
The project is failing on the following line:
projects.AddRange(abc.Database.SqlQuery<abc_Employees>("usp_ABC_EmployeeSys"));
And the error says: "Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding"
Everything was working fine a few days ago, and now, nothing. Nothing's changed either as far as code, or sql stored proc.
Anyone else experienced this before?
Did you try to run SP independently to see if that's the bottle neck?
Is it the command that is timing out?
You can increase the command timeout using:
((IObjectContextAdapter)abc).ObjectContext.CommandTimeout = 180;
You should take a look at your stored procedure. The default timeout is 30 seconds so it looks like it is taking longer for the stored procedure to return results. Increasing the timeout is just treating the symptoms.

Orchard.Alias.Implementation.Updater.AliasHolderUpdater - Exception during Alias refresh

crosspost: https://orchard.codeplex.com/discussions/473454
I want to start by saying I'm currently migrating from Orchard CMS 1.6 to 1.7.2. So it used to work in 1.6 but I'm now having issues with 1.7.2.
2 of my Content Types are having issues when creating items, they never finish saving and when I check the logs I get this:
Orchard.Alias.Implementation.Updater.AliasHolderUpdater - Exception during Alias refresh
NHibernate.Exceptions.GenericADOException: could not execute query
[ select aliasrecor0_.Id as Id1829_, aliasrecor0_.Path as Path1829_, aliasrecor0_.RouteValues as RouteVal3_1829_, aliasrecor0_.Source as Source1829_, aliasrecor0_.Action_id as Action5_1829_ from Orchard_Alias_AliasRecord aliasrecor0_ where aliasrecor0_.Id>#p0 order by aliasrecor0_.Id asc ]
Name:p1 - Value:48
[SQL: select aliasrecor0_.Id as Id1829_, aliasrecor0_.Path as Path1829_, aliasrecor0_.RouteValues as RouteVal3_1829_, aliasrecor0_.Source as Source1829_, aliasrecor0_.Action_id as Action5_1829_ from Orchard_Alias_AliasRecord aliasrecor0_ where aliasrecor0_.Id>#p0 order by aliasrecor0_.Id asc] ---> System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. ---> System.ComponentModel.Win32Exception: The wait operation timed out
When I stop it and view the site (anywhere really), it's entirely wrecked with this error:
Exception Details: System.ComponentModel.Win32Exception: The wait operation timed out
[Win32Exception (0x80004005): The wait operation timed out]
[SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.]
Line 162: return criteria
Line 163: .List<ContentItemVersionRecord>()
Line 164: .Select(x => ContentManager.Get(x.ContentItemRecord.Id, _versionOptions != null && _versionOptions.IsDraftRequired ? _versionOptions : VersionOptions.VersionRecord(x.Id)))
Source File: d:\Projects\Office Ignite\Main-1.7\src\Orchard\ContentManagement\DefaultContentQuery.cs Line: 162
I don't know why this is isolated with those two CTs. They don't have parts with custom tables or anything.
Any piece of information would be highly appreciated. Thanks!
I have same error, but it seems that problem is not related directly for my code.
I found two solutions for now:
1.) Taxonomy corruption problem https://orchard.codeplex.com/workitem/20411
2.) Static is dirty and lock which is default in select statment is heavly used https://serverfault.com/questions/419997/the-wait-operation-timed-out-when-running-sql-server-in-hyper-v