ASP.NET Entity Framework Update SQL set int value to 0 - sql-server

I have a SQL column as an int data type.
I'm trying to update en entry using Entity Framework, setting it's value to 0 but it does not get updated. I also don't get an error when Submitting Changes... Odd. Well I changed the Tag Name and set the count to 0, the name got updated but the count was not modified
Any ideas?
Thanks in advance
Code Snipet:
Add Tag - up the tag count:
Tag tag = _tagsRepository.GetTagByName(TagName);
if (tag == null)
{
tag = new Tag();
tag.CreateDate = DateTime.Now;
tag.Name = TagName;
tag.Count = 1;
}
else
{
tag.Count += 1;
}
tag = _tagsRepository.SaveTag(tag);
Remove tag from an item, update the tag count
Tag tag = _tagsRepository.GetTagByName(TagName);
if (tag != null)
{
tag.Count -= 1;
}
tag = _tagsRepository.SaveTag(tag);
GetTagByName Method
public Tag GetTagByName(string Name)
{
Tag result = null;
using (ISADataContext dc = conn.GetContext())
{
result = dc.Tags.Where(t => t.Name == Name).FirstOrDefault();
}
return result;
}
SaveTag Method
public Tag SaveTag(Tag tag)
{
using (ISADataContext dc = conn.GetContext())
{
if (tag.TagID > 0)
{
dc.Tags.Attach(new Tag { TagID = tag.TagID });
dc.Tags.ApplyCurrentValues(tag);
}
else
{
dc.Tags.AddObject(tag);
}
dc.SaveChanges();
}
return tag;
}
Workaround:
using (ISADataContext dc = conn.GetContext())
{
if (tag.TagID > 0)
{
if (tag.Count == 0)
{
Tag t = dc.Tags.Where( tt=> tt.TagID == tag.TagID).First();
t.Count = 0;
}
else
{
dc.Tags.Attach(new Tag { TagID = tag.TagID });
dc.Tags.ApplyCurrentValues(tag);
}
}
else
{
dc.Tags.AddObject(tag);
}
dc.SaveChanges();
}
return tag;

You shouldn't wrap your DataContext in using statements in your scenario. Doing this means that you're retrieving the object in one context and trying to save the existing object in a new context. This means that when you're trying to save in the second context, it has no idea that the object already exists in the database.

I ran into the same problem as yours - every other value except 0 works fine. Can we get some solution to this?
EDIT: After some research, I found a way to fix this. You have to modify this line:
dc.Tags.Attach(new Tag { TagID = tag.TagID });
In the stub object, add the problematic property (in your case Count) and set its value to something that is never possible in the db, for example -2. In this way, the EF context will also compare the count value of the attached object and will always know there is a difference. So your line becomes:
dc.Tags.Attach(new Tag { TagID = tag.TagID, Count = -2 });
I am not sure if this will work every time, but for now it seems to do the job.

Related

I am new to Apex development and trying to compile this code but failing

public class InstanceTriggerHandler {
public static void createInstanceHistoryRecord(Map<ID,Instance__c> newMap, Map<ID,Instance__c> oldMap) {
List<Instance_History__c > listOfIntHistoryToCreate = new List<Instance_History__c >();
List<Schema.FieldSetMember> trackedFields = SObjectType.Instance__c.FieldSets.Case_View.getFields();
if (trackedFields.isEmpty()) return;
for(Instance__c ins:newMap.values()) {
for (Schema.FieldSetMember fst : trackedFields) {
String fieldName = fst.getFieldPath();
String fieldLabel = fst.getLabel();
Instance__c oldInstance = (oldMap != null) ? oldMap.get(ins.id) : new Instance__c();
if (ins.get(fieldName) != oldInstance.get(fieldName)) {
String newValue = String.valueOf(ins.get(fieldName));
String oldValue = String.valueOf(oldInstance.get(fieldName));
if (oldValue != null && oldValue.length()>255) {
oldValue = oldValue.substring(0,255);
}
if (newValue != null && newValue.length()>255) {
newValue = newValue.substring(0,255);
}
final Instance_History__c instanceHistory = new Instance_History__c();
instanceHistory.Field__c = fieldLabel;
instanceHistory.Instance__c = ins.Id;
instanceHistory.Field_API__c = fieldName;
instanceHistory.Original_Value__c = oldValue;
instanceHistory.New_Value__c = newValue;
listOfIntHistoryToCreate.add(instanceHistory);
}
}
}
if(!listOfIntHistoryToCreate.isEmpty()) {
insert listOfIntHistoryToCreate;
}
}
}
Apex is giving me an error.
"Invalid type: Schema.Instance_History".
I already checked my custom object and it indeed has double underscores in code everywhere it is referenced. Can someone help?
Field history objects for custom objects need 2 underscores, try Instance__History. Probably easiest for you is to use http://workbench.developerforce.com/ to see all objects? You ever used "describe" operations?
https://help.salesforce.com/s/articleView?id=sf.tracking_field_history.htm&type=5
Salesforce stores an object’s tracked field history in an associated
object called StandardObjectNameHistory or CustomObjectName__History.
For example, AccountHistory represents the history of changes to the
values of an Account record’s fields. Similarly,
MyCustomObject__History tracks field history for the MyCustomObject__c
custom object.
Schema.SObjectType.Instance__c.FieldSets.Case_View.getFields();

Angular 2: Delete object in Array

I want to delete an object in an array when that object's ID is equal to the ID of the object getting compared. Currently, it only removes the first object in the array
if(this.selectedProducts.length > 0){
for(let x of this.selectedProducts){
if(prod._id === x._id){
this.selectedProducts.splice(x,1); //this is the part where I 'delete' the object
this.appended = false;
}else{
this.appended = true;
}
}
if (this.appended) {
this.selectedProducts.push(prod);
}
}else{
this.selectedProducts.push(prod);
}
this.selectEvent.emit(this.selectedProducts);
}
this.selectedProducts.splice(x,1);
The first parameter to splice must be the index, not the object.
If you're using for...of, you can't get the index easily. So you should use a regular for loop instead. With some additional simplifications, your code would look like this:
for (let i = this.selectedProducts.length - 1; i >= 0; this.selectedProducts.length; i--) {
if (prod._id === this.selectProducts[i]._id) {
this.selectedProducts.splice(i, 1); //this is the part where I 'delete' the object
}
}
this.selectedProducts.push(prod);
It's highly likely that using filter would be better anyway:
this.selectedProducts = this.selectedProducts.filter(x => prod._id !== x._id).concat(prod);

AngularJS mysql filter multiple element

Hi this is my hotel project. But I'm having a problem with a filter.
I want to filter the data in the amenities column.
This is: my fiddle
It works if you select a single checkbox but it does not work if you select multiple checkboxes.
I suspect the problem arises from indexof instead of what I can use. What method should I follow?
How to change this line: indexOf(x);
This is my bad code:
//PROBLEM FILTER HERE
$scope.am_en = function()
{
//get input value
x = $(".hosting_amenities input:checkbox:checked").map(function(){return $(this).val();}).get();
//filter
$scope.ot_Filter = function (location) {
return location.amenities.indexOf(x) !== -1;
};
}
The problem is indeed caused by the function $scope.am_en, in the declaration of the inner function $scope.ot_Filter
When you select multiple checkboxes, your x variable is an array of objects, so you should do a loop and can create a variable to check whether the element should be shown or not. You can do it as follows:
$scope.ot_Filter = function (location) {
var shouldBeShown = false;
for (var i = 0; i < x.length; i++) {
if (location.amenities.indexOf(x[i]) !== -1) {
shouldBeShown = true;
break;
}
}
return shouldBeShown;
};
I modified your jsfiddle, so that you can see this solution working properly.

Sitecore doesn't remove records from custom solr index

I have strange issue when I am trying to remove some records from custom solr index.
I created code like this
public void DeleteRecordsFromIndex(string indexName,IEnumerable<IIndexableUniqueId> uniqueIds)
{
if (uniqueIds == null || string.IsNullOrEmpty(indexName) || !uniqueIds.Any())
{
return;
}
using (IProviderDeleteContext deleteContext = ContentSearchManager.GetIndex(indexName).CreateDeleteContext())
{
foreach (var indexId in uniqueIds)
{
deleteContext.Delete(indexId);
}
deleteContext.Commit();
}
}
Search Item property when I need to get UniqueId
[IndexField("_uniqueid")]
public IIndexableUniqueId UniqueId
{
get
{
return new `enter code here`IndexableUniqueId<string>(this.Uri.ToString());
}
}
Based on debug info IIndexableUniqueId contains correct values
like:"sitecore://web/{66d75448-72a5-4d94-9788-61c6c64b9251}?lang=en-au&ver=1"
what is equal to _uniqueid field in solr index.
I had 4 records in my custom solr index.
After first run one records was removed from index, But 3 records are steel there.
I have ran code couple of times, but 3 records always inside of index.
What could be wrong with my code ?
I found solution:
insted of using IIndexableUniqueId it is better to use IIndexableId
public IIndexableId GetIndexableId(ID itemId)
{
//map to _group value
var id = itemId.ToString().ToLower().Replace("{", "").Replace("}", "").Replace("-", "");
return new IndexableId<string>(id);
}
public int DeleteRecordsFromIndex(string indexName, IIndexableId uniqueIds)
{
if (uniqueIds == null || string.IsNullOrEmpty(indexName))
{
return -1;
}
using (var deleteContext = ContentSearchManager.GetIndex(indexName).CreateDeleteContext())
{
var resuls = deleteContext.Delete(uniqueIds);//this method use _group fields for remove records. All languages will be removed.
deleteContext.Commit();
return resuls;
}
}
regarding ILSpy, sitecore remove item by _group
// Sitecore.ContentSearch.SolrProvider.SolrUpdateContext
public void Delete(IIndexableId id)
{
Assert.ArgumentNotNull(id, "id");
object obj = this.index.Configuration.IndexFieldStorageValueFormatter.FormatValueForIndexStorage(id);
SolrQueryByField solrQueryByField = new SolrQueryByField("_group", obj.ToString());
SolrQueryByField solrQueryByField2 = new SolrQueryByField("_indexname", this.index.Name);
this.solr.Delete(solrQueryByField && solrQueryByField2);
this.CommitPolicyExecutor.IndexModified(this, id, IndexOperation.Delete);
}

Angular ng-repeat filtering

I have a deeply nested object. I have some records which contain 2 fields that show keys of object properties. I also have select needed to search records by property of object and input to search by key of object. So if I choose option1 and type in input some text, it will be shown the matches in the first field (not second!). And it's similar for second field.
How I try to realize:
I wrote a filter http://plnkr.co/edit/z9DEmfYz2grW9UonLcFK?p=preview
.filter('appFilter', function() {
return function(value, select, input) {
var result = [];
input = input.toLowerCase();
var reg = new RegExp(input,'g');
if (angular.isArray(value)) {
if (input === '' || $scope.isFiltering) {
return value;
} else if (select.value === 'Sequence') {
for (let i = 0; i < value.length; i++) {
if (value[i].Sequence.toLowerCase().match(reg)) {
result.push(value[i]);
}
}
return result;
} else if (select.value === 'ID') {
for (let i = 0; i < value.length; i++) {
if (angular.isArray(value[i].Document)) {
for (let j = 0; j < value[i].Document.length; j++) {
if (value[i].Document[j].ID.toLowerCase().match(reg)) {
result.push(value[i]);
}
}
}
}
return result;
} else {
console.log('error');
}
}
}
})
In controller I set to select's ng-model first option: $scope.selectParameter = $scope.parameter[0];
In debug I set to input parameter some value (123 for example).
So I searching record by first field that contains 123 value. And result finds and pushes the object. But in browser shows anything.
What's the problem? And I can't avoid the empty option with '?' value in my select :(
UPDATED
Nearly solve my problem: http://plnkr.co/edit/z9DEmfYz2grW9UonLcFK?p=preview
It filters by appropriate field and input value. But I faced with another troubles.
When input is empty it doesn't show any record. And second is when I choose second option (ID) filter duplicates some records.
Also I try to switch off filter without clearing the input text by clicking on checkbox.
It's what I want to do but it doesn't work:
else if (input === '' || $scope.isFiltering) {
return value;
}
$scope.isFiltering is ng-model for checkbox input
I tried using angulars default filter. I'm not sure if this is exactly what you want, but maybe it helps a little.
.filter('appFilter', function($filter) {
return function(value, select, input) {
if( !angular.isDefined(input) || input.length < 1) {
return value;
}
// Angulars "filter" lets you pass in a object-structure to search for nested fields.
var query =
(select.value === 'Sequence') ?
{Sequence:input} : {Document:{ID:input}};
return $filter('filter')(value, query);
}
})
http://plnkr.co/edit/Egkw9bUvTPgooc0u2w7C?p=preview

Resources