I set a 3-column index that must be unique in my table. How can I tell EF that? I'm currently getting a DbUpdateException when trying to save the changes.
Cannot insert duplicate key row in object 'sm.SkillAssignations' with unique index 'IX_SkillAssignations'. The duplicate key value is (8285, 1, 2, 2).\r\nThe statement has been terminated.
In order to avoid the exception check if an entity with the unique index value you want to insert already exists:
if (!context.SkillAssignations.Any(s =>
s.Value1 == newSkillAssignation.Value1 &&
s.Value2 == newSkillAssignation.Value2 &&
s.Value3 == newSkillAssignation.Value3))
context.SkillAssignations.Add(newSkillAssignation);
else
// your own error handling
// - or do you want to UPDATE the existing entity in this case?
It could still fail if someone else inserts an entity with that key between the Any call (EXISTS query) and the Add (INSERT statement). I am not aware of any magic that would save you this check.
Related
I am trying to check if a value is in SQLite with python to then either update the table if the value exists or create a new value if it is not. I have tried to create a cursor to check rows, append the rows to a list with loop, check if value exists, check the count of the rows... I seems to get hung up on the if statement when trying to access the value initialized from the query. Here is the code:
checkT = db.execute("SELECT COUNT(*) FROM trans WHERE stock=:stock AND id=:user_id", stock=request.form.get("symbol"), user_id=session["user_id"])
if checkT > 0:
print("there")
else:
print("not there")
How can I fix this? Thank you!
From the CS50 Library for Python doc for execute
Returns
for SELECTs, a list of dict objects, each of which represents a row in the result set; for INSERTs, the primary key of a newly inserted row (or None if none); for UPDATEs, the number of rows updated; for DELETEs, the number of rows deleted; for CREATEs, True on success; on error, a RuntimeError is raised
checkT is a list with one element, which is a dict with one key/value pair.
This checkT[0]['COUNT(*)'] will give the number returned from the sql. Counting the rows would not be appropriate in this case because this query will always return one row.
One hint: column names in a SELECT can be aliased, given a different name, like so:
SELECT COUNT(*) as count from....... It would just be typing convenience, because then the key in the returned dict will be count instead of COUNT(*).
Remember: in the flask run terminal there is a traceback with gives more details information on the error received (assuming "hung up" means a 500 Internal Server Error).
Is there a way to get the index of the results within an aql query?
Something like
FOR user IN Users sort user.age DESC RETURN {id:user._id, order:{index?}}
If you want to enumerate the result set and store these numbers in an attribute order, then this is possible with the following AQL query:
LET sorted_ids = (
FOR user IN Users
SORT user.age DESC
RETURN user._key
)
FOR i IN 0..LENGTH(sorted_ids)-1
UPDATE sorted_ids[i] WITH { order: i+1 } IN Users
RETURN NEW
A subquery is used to sort users by age and return an array of document keys. Then a loop over a numeric range from the first to the last index of the that array is used to iterate over its elements, which gives you the desired order value (minus 1) as variable i. The current array element is a document key, which is used to update the user document with an order attribute.
Above query can be useful for a one-off computation of an order attribute. If your data changes a lot, then it will quickly become stale however, and you may want to move this to the client-side.
For a related discussion see AQL: Counter / enumerator
If I understand your question correctly - and feel free to correct me, this is what you're looking for:
FOR user IN Users
SORT user.age DESC
RETURN {
id: user._id,
order: user._key
}
The _key is the primary key in ArangoDB.
If however, you're looking for example data entered (in chronological order) then you will have to have to set the key on your inserts and/or create a date / time object and filter using that.
Edit:
Upon doing some research, I believe this link might be of use to you for AI the keys: https://www.arangodb.com/2013/03/auto-increment-values-in-arangodb/
I am merging two tables
Table 1's primary key exists in table 2 but in some case there is no key foreign in table 2. Which fires error that there is no key exists.
I want to merge table with condition only if key exists;
r.table('sport').filter({sport_id:sport_id}).merge(function(doc){
return {
terminology: r.table('sport_terminology').get(doc("terminology_id"))
}
})
.run(conn, sport);
Now if sport does not contain terminology as key than it is firing error. Please give me solution for merge bypass if key does not exists
It is a bit unclear from your question what is it that you're having trouble with, since you haven't posted the exception you're getting.
I assume that for some documents, you're getting a "No attribute 'terminology_id' in object". If that's the case, simply add a default() value, e.g:
r.table('sport').filter({sport_id:sport_id}).merge(function(doc) {
return {
terminology: r.table('sport_terminology')
.get(doc("terminology_id").default(null))
}
})
If it's not the case, please post the error message.
I have a Dynamics CRM Plugin registered in "Pre Validation" and trigger on delete.
I have inside it a LINQ query that retrieve the maximum value of a date field of children records for a particular parent record.
Here is my code:
var q = (from e1 in serviceContext.CreateQuery<entity1>()
join e2 in serviceContext.CreateQuery<entity2>() on e1.typeid.Id equals e2.codeId
where e1.statecode == 0 && e1.ParentId.Id.Equals(new Guid(ParentGuidStr))
orderby e1.dt descending
select new {e1.dt, e2.code}).ToList();
I am getting the following error on the above query When the record that the plugin triggers on is INACTIVE:
PreValidateEntity1Delete PlugIn Error:
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. ---> System.ArgumentNullException:
Value cannot be null. Parameter name: g
I am NOT sure why I am getting the above error and if the link between an inactive children record and a parent record got broken in a LINQ query or there is another reason.
First, please ensure all children records have reference to parent record.
Then, change your where contidion into:
where e1.statecode == 0 && e1.ParentId != null && e1.ParentId.Id.Equals(new Guid(ParentGuidStr))
The problem is that an EntityReference field (e1.ParentId) may be null and when you tried access a null entity, the error appears.
Then because of that, you should also make sure e1.typeid is not null in the join condition too.
Or, you can try a workaround with 2 separate queries, and collect information from their results.
Good luck!
I have a set of tables (ConditionTemplate and KeyWord) that have a many to many relationship. In code I am trying to add a Keyword to a specific ConditionTemplate record. Unfortunately, when I think I'm adding a Keyword to a specific condition I'm getting an error as if it's adding a new Keyword without being associated to a condition.
An Image of my Model:
My Code:
Global Variables Creation:
EnterpriseEntities EE;
ConditionTemplate myConditionTemplate;
Load Global Variables:
EE = new EnterpriseEntities();
EE.Database.Connection.ConnectionString = Myapp.EnterpriseEntityConnectionString;
myConditionTemplate = EE.ConditionTemplates.Where(c => c.TemplateCode == "17D").FirstOrDefault();
The above code loads a single Condition with Many Keywords.
Available Keywords are in a listbox and the user pushed a button to select a keyword(s) to move to the condition. This is the code that handles that.
foreach (KeyWord SelectedKeyWord in ListBoxAvailableKeyWords.SelectedItems)
{
KeyWord NewKeyWord = new KeyWord
{
KeyWordID = SelectedKeyWord.KeyWordID,
ID = SelectedKeyWord.ID,
Word = SelectedKeyWord.Word
};
myConditionTemplate.KeyWords.Add(NewKeyWord);
}
Then the user pushes a button to save changes and I call
EE.SaveChanges
Then I get this error:
System.Data.UpdateException: An error occurred while updating the
entries. See the inner exception for details. --->
System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint
'IX_KeyWord'. Cannot insert duplicate key in object 'dbo.KeyWord'. The
duplicate key value is (ADJUDICATION). The statement has been
terminated.
If I remove the code that sets the word property (Word = SelectedKeyWord.Word
) when I create the keyword object I get this error.
System.Data.Entity.Validation.DbEntityValidationException: Validation
failed for one or more entities. See 'EntityValidationErrors' property for more details.
Which tells me the word field is required.
In order to tell EF that the KeyWords you selected already exist in the database and to avoid the problem you must attach them to the context:
foreach (KeyWord SelectedKeyWord in ListBoxAvailableKeyWords.SelectedItems)
{
KeyWord NewKeyWord = new KeyWord
{
// You actually only need to set the primary key property here
ID = SelectedKeyWord.ID
};
EE.KeyWords.Attach(NewKeyWord);
myConditionTemplate.KeyWords.Add(NewKeyWord);
}
Edit
If the KeyWord entities are already attached to your context (because they have been loaded before with the same context for example) you can use instead:
foreach (KeyWord SelectedKeyWord in ListBoxAvailableKeyWords.SelectedItems)
{
KeyWord NewKeyWord = EE.KeyWords.Find(SelectedKeyWord.ID);
myConditionTemplate.KeyWords.Add(NewKeyWord);
}