telerik mvc Create CompositeFilterDescriptor and append it to existing datasource request filter - filtering

I am having some issues creating a CompositeFilterDescriptor from scratch.
The scenario: We have date filters on the grid, but are showing date time fields.
When Someone filters to a specific date, we show all records for that day.
when someone filters greater than that day, we edit the filterDescriptor for that filter and add one day to it.
when someone filters to less than or equal to that day, we edit the filterdescriptor for that filter and add one day to it.
Here is the problem: when someone selects "not equal to", the solution would be to create a compositeFilterDescriptor containing two filters. One for less than that day, one for greater than that day.
I may ore may not be doing this part properly. I can not figure out how to add the new compositeFilterDescriptor to the existing dataSourceRequest.
Here is what I have:
static public DataSourceRequest FixDateFilters(DataSourceRequest request, string[] optionalFields = null)
{
if (request?.Filters != null)
{
List<string> matchingFields = new List<string> { "utc", "time" };
List<FilterDescriptor> newDescriptors = new List<FilterDescriptor>();
//if any fields specific to a page have been passed in, append them to the list.
if (optionalFields != null)
{
foreach (string field in optionalFields)
matchingFields.Append(field);
}
foreach (string matchingField in matchingFields)
{
List<FilterDescriptor> descriptors = new List<FilterDescriptor>();
FilterDescriptor descriptor1 = FindFirstFilterByMember(request.Filters, matchingField, true, null);
//there could be up to two filters on a matching field. Get the 2nd one if it exists.
FilterDescriptor descriptor2 = FindFirstFilterByMember(request.Filters, matchingField, true, descriptor1);
//turn the matches into a list for iterating
if (descriptor1 != null)
descriptors.Add(descriptor1);
if (descriptor2 != null)
descriptors.Add(descriptor2);
if (descriptors.Count != 0)
{
foreach (FilterDescriptor descriptor in descriptors)
{
DateTime? utcDate = (DateTime?)descriptor?.Value;
if (utcDate.HasValue)
{
utcDate = Core.DateHelper.ToUTC(utcDate.Value, HttpContext.Current); //make sure date ranges are one day ranges in local time
}
if (utcDate != null)
{
if (descriptor.Operator == FilterOperator.IsLessThanOrEqualTo)
{
utcDate = ((DateTime)utcDate).AddDays(1);
descriptor.Value = utcDate;
}
else if (descriptor.Operator == FilterOperator.IsGreaterThan)
{
utcDate = utcDate.Value.AddDays(1);
descriptor.Value = utcDate;
}
else if (descriptor.Operator == FilterOperator.IsEqualTo)
{
descriptor.Operator = FilterOperator.IsGreaterThanOrEqualTo;
newDescriptors.Add(new FilterDescriptor(descriptor.Member, FilterOperator.IsLessThan, utcDate.Value.AddDays(1)));
}
else if (descriptor.Operator == FilterOperator.IsNotEqualTo)
{
CompositeFilterDescriptor cfd = new CompositeFilterDescriptor();
cfd.LogicalOperator = FilterCompositionLogicalOperator.Or;
cfd.FilterDescriptors.Add(new FilterDescriptor(descriptor.Member, FilterOperator.IsLessThan, utcDate.Value;));
cfd.FilterDescriptors.Add(new FilterDescriptor(descriptor.Member, FilterOperator.IsGreaterThan, utcDate.Value.AddDays(1)));
newDescriptors.Add( cfd);
}
}
}
}
}
//equals matches add a new descriptor so add them after the foreach is done so they don't affect the foreach.
foreach (FilterDescriptor newDescriptor in newDescriptors)
{
if (newDescriptor.Member != "") //a blank descriptor has a emptry string for member
{
request.Filters.Add(newDescriptor);
}
}
}
return request;
}
}
static public FilterDescriptor FindFirstFilterByMember(IEnumerable<IFilterDescriptor> filters, string findMember, bool partialMatch = false, FilterDescriptor previous = null)
{
FilterDescriptor ret = null;
foreach (var filter in filters)
{
var descriptor = filter as FilterDescriptor;
if (descriptor != null
&& (descriptor.Member == findMember || (partialMatch == true && descriptor.Member.ToLower().Contains(findMember.ToLower())))
&& (previous == null || previous != descriptor))
{
ret = descriptor;
break;
}
else if (filter is CompositeFilterDescriptor)
{
ret = FindFirstFilterByMember(((CompositeFilterDescriptor)filter).FilterDescriptors, findMember, partialMatch, previous);
if (ret != null)
break;
}
}
return ret;
}
The second function is a recursive one for getting the filters by string.
The problem section is the "isNotEqualTo" comparison. I don't know how to save the composite filter into the existing request. It gives me a casting error.

Ok it turns out all i needed to do was create a new list of CompositeFilterDescriptor type and append that when necessary. The .add function took both. Sigh.
foreach (CompositeFilterDescriptor newCompositeDescriptor in newCompositeDescriptors)
{
request.Filters.Add(newCompositeDescriptor);
}

Related

Getting WorkbookPart from row

I am writing and extension for OpenXML like shown in the sample. I would like to avoid having to pass the WorkbookPart as parameter. Is there any way to get the WorkbookPart directly from the row?
public static string GetCellTextValue(this Row row, WorkbookPart workbookPart, string column)
{
var cells = row.Elements<Cell>();
var cell = cells.Where(p => p.CellReference == column + row.RowIndex.ToString()).FirstOrDefault();
if (cell.DataType != null)
{
if (cell.DataType == CellValues.SharedString)
{
int id = -1;
if (Int32.TryParse(cell.InnerText, out id))
{
SharedStringItem item = workbookPart.SharedStringTablePart.SharedStringTable.Elements<SharedStringItem>().ElementAt(id);
if (item.Text != null)
{
return item.Text.Text;
}
else if (item.InnerText != null)
{
return item.InnerText;
}
else if (item.InnerXml != null)
{
return item.InnerXml;
}
}
}
}
return string.Empty;
}
Unfortunately, none of the strongly-typed classes of the Open XML SDK (e.g., Workbook, Worksheet, Row) have properties pointing back to the OpenXmlPart (e.g., WorkbookPart, WorksheetPart) in which they are contained or any other part related to their immediate container. Unless you amend your API in other ways, you will have to pass that WorkbookPart.

Only Update Entity (Parent or children) if Property Values Have Changed with EF

As I build a project with Entity Framework 6 (using EF for the first time), I noticed that when I only Update the relationships of an Entity, EF updates the main Entity too.
I can tell this is happening because I'm using System Versioned tables on Sql Server 2017.
This is a made up scenario, but most of the concept is here.
public async Task<ActionResult> Edit([Bind(Include="Id,Name,LocationTimes")] LocationViewModel locationVM) {
if (ModelState.IsValid) {
var location = await _db.Locations.FirstOrDefaultAsync(l => l.Id == locationsViewModel.Id && l.UserId == UserId);
if (location == null) {
return HttpNotFound();
}
location.Name = locationsViewModel.Name;
// ... other properties
foreach (var day in locationsViewModel.LocationTimes.Days) {
var time = new Time {
Day = day.Day,
OpenTime = day.OpenTime,
CloseTime = day.CloseTime,
};
// Find current Time or keep newly created
time = await time.FindByTimeAsync(time, _db) ?? time;
// Find LocationTime with same day
var locationTime = location.LocationTimes.FirstOrDefault(lt => lt.Time.Day == day.Day);
// If all times are the same, skip (continue)
if (locationTime != null && locationTime.Time.OpenTime == time.OpenTime && locationTime.Time.CloseTime == time.CloseTime)
continue;
if (locationTime != null && (locationTime.Time.OpenTime != time.OpenTime || locationTime.Time.CloseTime != time.CloseTime)) {
// Remove, At least one of the Times do not match
locationTime.Time = time;
_db.Entry(locationTime).State = EntityState.Modified;
} else {
location.LocationTimes.Add(new LocationTime {
Location = location,
Time = time,
});
}
}
_db.Entry(location).State = EntityState.Modified;
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}
}
I assume, that by marking the entire Entity as Modified, EF will call the update statement.
How can I avoid an UPDATE to the parent Entity, if no properties have changed on the parent, but still Add/Update the child relationships?
I assume I have to check that each property has not changed and therefore I should not be setting location state to Modified, but how would I handle the newly added Times?
Update #1
So I tried what I mentioned and it works, but is this the correct way to do this?
public async Task<ActionResult> Edit([Bind(Include="Id,Name,LocationTimes")] LocationViewModel locationVM) {
if (ModelState.IsValid) {
var location = await _db.Locations.FirstOrDefaultAsync(l => l.Id == locationsViewModel.Id && l.UserId == UserId);
if (location == null) {
return HttpNotFound();
}
/*******************
This is new part
*******************/
if (
location.Name != locationsViewModel.Name
// || ... test other properties
) {
location.Name = locationsViewModel.Name;
// ... other properties
_db.Entry(location).State = EntityState.Modified;
} else {
_db.Entry(location).State = EntityState.Unchanged;
}
/*******************/
foreach (var day in locationsViewModel.LocationTimes.Days) {
var time = new Time {
Day = day.Day,
OpenTime = day.OpenTime,
CloseTime = day.CloseTime,
};
// Find current Time or keep newly created
time = await time.FindByTimeAsync(time, _db) ?? time;
// Find LocationTime with same day
var locationTime = location.LocationTimes.FirstOrDefault(lt => lt.Time.Day == day.Day);
// If all times are the same, skip (continue)
if (locationTime != null && locationTime.Time.OpenTime == time.OpenTime && locationTime.Time.CloseTime == time.CloseTime)
continue;
if (locationTime != null && (locationTime.Time.OpenTime != time.OpenTime || locationTime.Time.CloseTime != time.CloseTime)) {
// Remove, At least one of the Times do not match
locationTime.Time = time;
_db.Entry(locationTime).State = EntityState.Modified;
} else {
location.LocationTimes.Add(new LocationTime {
Location = location,
Time = time,
});
}
}
/* removed, added above */
//_db.Entry(location).State = EntityState.Modified;
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}
}
So after trial and error, I guess I misunderstood how EF handles the EntityState. I though if a child was Modified, you had to set the parent as Modified as well.
Gladly, that's not the case and the code below works as desired.
public async Task<ActionResult> Edit([Bind(Include="Id,Name,LocationTimes")] LocationViewModel locationVM) {
if (ModelState.IsValid) {
var location = await _db.Locations.FirstOrDefaultAsync(l => l.Id == locationsViewModel.Id && l.UserId == UserId);
if (location == null) {
return HttpNotFound();
}
/*******************
This is new part
check if at least one property was changed
*******************/
if (
location.Name != locationsViewModel.Name
|| location.Ref != locationsViewModel.Ref
// || ... test other properties
) {
location.Name = locationsViewModel.Name;
location.Ref = locationsViewModel.Ref;
// ... other properties
// Tell EF that the Entity has been modified (probably not needed, but just in case)
_db.Entry(location).State = EntityState.Modified;
} else {
// Tell EF that the Entity has *NOT* been modified
_db.Entry(location).State = EntityState.Unchanged;
}
/*******************/
foreach (var day in locationsViewModel.LocationTimes.Days) {
var time = new Time {
Day = day.Day,
OpenTime = day.OpenTime,
CloseTime = day.CloseTime,
};
// Find current Time or keep newly created
time = await time.FindByTimeAsync(time, _db) ?? time;
// Find LocationTime with same day
var locationTime = location.LocationTimes.FirstOrDefault(lt => lt.Time.Day == day.Day);
// If all times are the same, skip (continue)
if (locationTime != null && locationTime.Time.OpenTime == time.OpenTime && locationTime.Time.CloseTime == time.CloseTime)
continue;
if (locationTime != null && (locationTime.Time.OpenTime != time.OpenTime || locationTime.Time.CloseTime != time.CloseTime)) {
// Remove, At least one of the Times do not match
locationTime.Time = time;
_db.Entry(locationTime).State = EntityState.Modified;
} else {
location.LocationTimes.Add(new LocationTime {
Location = location,
Time = time,
});
}
}
/* removed, added above */
//_db.Entry(location).State = EntityState.Modified;
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}
}

Deleting the head of doubly linked list

Sorry for such a low quality question but I have no idea why the following code doesn't work.
list points the head of the node.
void DeleteHeadNode(Node** list, Node * node)
{
if ((*list) == node) {
Node * next = node->nextnode;
next->prevnode = NULL;
free(*list);
}
}
The usage of Node** is used as alias. If passed the address of a list variable, one may alter it, by altering the Node* value.
In this way one set the passed list variable to null or to the second node.
The following is a usage pattern.
void DeleteNode(Node** list, int data)
{
while (*list != NULL && (*list)->data != data) {
list = &(node->nextnode);
}
if (*list != NULL) {
Node* found = *list;
*list = found->nextnode;
if (found->nextnode != NULL) {
found->nextnode->prevnode = *list;
}
free(found);
}
}
Usage:
Node* list;
...
DeleteNode(&list, ...);
A previous node (prevnode, a double linked list) is not really necessary.
The while loop is of interest: there the alias list is set from the list head to the address of a nextnode field. Hence a subsequent change of *list either changes the passed list variable or some nextnode field.
void SortedInsertNode(Node** list, int data)
{
Node* node = (Node*) malloc(sizeof(Node));
node->data = data;
node->prevnode = NULL;
node->nextnode = NULL;
while (*list != NULL && data >= (*list)->data) {
node->prevnode = *list;
list = &(node->nextnode);
}
node->nextnode = *list;
*list = node;
if (node->nextnode != NULL) {
node->nextnode->prevnode = *list;
}
}
Deleting the head:
void DeleteHead(Node** list)
{
if (*list != null) {
Node* dead = *list;
*list = (*list)->nextnode;
(*list)->prevnede = NULL;
free(dead);
}
}
I'm guessing "doesn't work" means list is no longer valid after your function - which will be true.
You should have
void DeleteHeadNode(Node** list, Node* node)
{
if ((node != NULL) && (*list == node)) // check node being deleted
{
Node* next = node->nextnode;
if (next != NULL) // ensure next exists
{
next->prevnode = NULL;
free(*list);
list = &next; // update pointer to head of list
}
else // no next, list is now becoming empty
{
free(*list);
list = NULL; // update pointer to head of list
}
}
}

Pagination not working for a Lazy Loaded Data Table on First Loading

I am using JPA named queries for Loading a Lazy Loaded DataTable. and setting first and Max results as shown below.
Query query = entityManager.createNamedQuery("StudyplanCategory.findByStatusAndLimit");
int end=(start*pageNumber);
query.setParameter("status", status);
query.setParameter("start", start);
query.setParameter("end", end);
query.setMaxResults(end - start);
The load method is given below:
public List<StudyplanCategory> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String,String> filters) {
List<StudyplanCategory> data = new ArrayList<StudyplanCategory>();
//System.out.println("Page First Value:"+first+"PageSize Value:"+pageSize);
datasource=categoryService.findDynaEditStudyPlan("NOT_USER_SPECIFIC",first,pageSize);
//filter
for(StudyplanCategory studyplanCategory : datasource) {
boolean match = true;
for(Iterator<String> it = filters.keySet().iterator(); it.hasNext();) {
try {
String filterProperty = it.next();
String filterValue = filters.get(filterProperty).toLowerCase();
String fieldValue = String.valueOf(studyplanCategory.getClass().getDeclaredField(filterProperty).get(studyplanCategory)).toLowerCase();
//System.out.println("fieldValue............."+fieldValue);
if(filterValue == null || fieldValue.startsWith(filterValue)) {
match = true;
}
else {
match = false;
break;
}
} catch(Exception e) {
match = false;
System.out.println("The Exception occured at"+e);
}
}
if(match) {
data.add(studyplanCategory);
}
}
//sort
if(sortField != null) {
Collections.sort(data, new LazySorter(sortField, sortOrder));
}
//rowCount
int dataSize = data.size();
this.setRowCount(dataSize);
//paginate
if(dataSize > pageSize) {
try {
return data.subList(first, first + pageSize);
}
catch(IndexOutOfBoundsException e) {
return data.subList(first, first + (dataSize % pageSize));
}
}
else {
return data;
}
}
But when the table is loaded Next Buttons are not active because I am loading only those data required to load the first page. How can I Solve this.
You need to fire another query which sets the total rowcount. Basically, in LazyDataModel#load():
public List<StudyplanCategory> load(...) {
setRowCount(studyplanCategoryService.count());
return studyplanCategoryService.list(...);
}
Unrelated to the concrete problem, you should actually be using Query#setFirstResult() to set the first record index.

Item's property inside a list changes value from EF source - is there a way to 'detach' it?

I have a list and this list is being populated thru loop. Each loop gets a collection directly from DB. The problem is that when it gets CaseNo(PK) that has the same CaseNo existing in the list and I changed the value of one of the property, the item that has the same CaseNo which is already in the list also changes.
ex. caseNo 1234, proc code = OTH
then I add another item which I get from DB again. but this time I programatically change the proc code, the item in the list above also changes to that value also.
I do not want that to happen because it is not the same Case in the record because a Case can have different type of pro code as its category.
I get that it is changing because it is detecting that it is the same item as the one in the list but I need to add the same case number in the list as a separate item because the proc code is different. Is there a way I can treat it as different entity as the one in the list?
Ex. of data
1.)CaseNO 123
Proc code OTH
2.) CaseNO 123
Proc code OTH
but I need it to be:
1.)CaseNO 123
Proc code DSP
1.)CaseNO 123
Proc code OTH
it goes wrong when this line is executed.
adrCase.ProcCode = "DSP";
then the item in the list (_adrMasterList) if there is any with the same case no, changes its proc code too to "DSP".
here is my code:
private void GenerateReport(string caseCoordinatorID) //LGF 08012011 ADR-59: add case coordinator - add parameter
{
var dispositions = FileMaintenanceBusiness.Instance.GetManyDispositionInfobyKeyword(_selectedProcCode, "ProcCode");
var adrDispos = FileMaintenanceBusiness.Instance.GetAllADRDispositionInfoList();
var calendarActivities = FileMaintenanceBusiness.Instance.GetManyCalendarActivityInfobyKeyword(_selectedProcCode, "ProcCode");
var adrCalActivities = FileMaintenanceBusiness.Instance.GetAllADRCalendars();
var otherActivities = FileMaintenanceBusiness.Instance.GetManyOtherActivities(_selectedProcCode, "ProcCode");
var adrOtherActivities = FileMaintenanceBusiness.Instance.GetAllADROtherActivities();
_adrMasterList.Clear();
if (_selectedProcCode == "ALL")
{
var dispositionALL = FileMaintenanceBusiness.Instance.GetAllDispositionInfoList();
var adrDisposALL = FileMaintenanceBusiness.Instance.GetAllADRDispositionInfoList();
var calendarActivitiesALL = FileMaintenanceBusiness.Instance.GetAllCalendarActivityInfoList();
var adrCalActivitiesALL = FileMaintenanceBusiness.Instance.GetAllADRCalendars();
var otherActivitiesALL = FileMaintenanceBusiness.Instance.GetAllOtherActivities();
var adrOtherActivitiesALL = FileMaintenanceBusiness.Instance.GetAllADROtherActivities();
if (dispositionALL != null && adrDisposALL != null)//dispos
{
foreach (var dispo in dispositionALL)
{
foreach (var adrDispo in adrDisposALL)
{
if (dispo.DispositionID == adrDispo.DispositionID)
{
var adrCase = FileMaintenanceBusiness.Instance.GetADRMasterInfobyKeyword(adrDispo.CaseNo, "CaseNo");
if (adrCase != null)
{
adrCase.ProcCode = "DSP";
adrCase.ProcDateString = dispo.ProcDate.HasValue ? dispo.ProcDate.Value.ToShortDateString() : string.Empty;
//LGF 08012011 ADR-59: add case coordinator - add CaseCoordinatorFilter
//if (!_adrMasterList.Contains(adrCase) && CaseCoordinatorFilter(caseCoordinatorID, adrCase.CaseNo))
// _adrMasterList.Add(adrCase);
if (CaseCoordinatorFilter(caseCoordinatorID, adrCase.CaseNo))
_adrMasterList.Add(adrCase);
}
}
}
}
}
if (calendarActivitiesALL != null && adrCalActivitiesALL != null)//cals
{
foreach (var cal in calendarActivitiesALL)
{
foreach (var adrCal in adrCalActivitiesALL)
{
if (cal.CalendarItemID == adrCal.CalendarItemID)
{
var adrCase = FileMaintenanceBusiness.Instance.GetADRMasterInfobyKeyword(adrCal.CaseNo, "CaseNo");
if (adrCase != null)
{
adrCase.ProcCode = "CAL";
adrCase.ProcDateString = cal.ProcDate.ToShortDateString();
//LGF 08012011 ADR-59: add case coordinator - add CaseCoordinatorFilter
//if (!_adrMasterList.Contains(adrCase) && CaseCoordinatorFilter(caseCoordinatorID, adrCase.CaseNo))
// _adrMasterList.Add(adrCase);
if (CaseCoordinatorFilter(caseCoordinatorID, adrCase.CaseNo))
_adrMasterList.Add(adrCase);
}
}
}
}
}
if (otherActivitiesALL != null && adrOtherActivitiesALL != null)//other activities
{
foreach (var otherActivity in otherActivitiesALL)
{
foreach (var adrotherActivity in adrOtherActivitiesALL)
{
if (otherActivity.ActivityID == adrotherActivity.ActivityID)
{
var adrCase = FileMaintenanceBusiness.Instance.GetADRMasterInfobyKeyword(adrotherActivity.CaseNo, "CaseNo");
if (adrCase != null)
{
adrCase.ProcCode = otherActivity.ProcCode;
adrCase.ProcDateString = otherActivity.ProcDate.ToShortDateString();
//LGF 08012011 ADR-59: add case coordinator - add CaseCoordinatorFilter
//if (!_adrMasterList.Contains(adrCase) && CaseCoordinatorFilter(caseCoordinatorID, adrCase.CaseNo))
if(CaseCoordinatorFilter(caseCoordinatorID, adrCase.CaseNo))
_adrMasterList.Add(adrCase);
}
}
}
}
}
}
else if (_selectedProcCode == "DSP")
{
if (dispositions != null && adrDispos != null)
{
foreach (var dispo in dispositions)
{
foreach (var adrDispo in adrDispos)
{
if (dispo.DispositionID == adrDispo.DispositionID)
{
var adrCase = FileMaintenanceBusiness.Instance.GetADRMasterInfobyKeyword(adrDispo.CaseNo, "CaseNo");
//LGF 08012011 ADR-59: add case coordinator - add CaseCoordinatorFilter
if (adrCase != null && CaseCoordinatorFilter(caseCoordinatorID, adrCase.CaseNo))
{
adrCase.ProcCode = _selectedProcCode;
//adrCase.ProcDateString = dispo.ProcDate.ToShortDateString();
_adrMasterList.Add(adrCase);
}
}
}
}
}
}
else if (_selectedProcCode == "CAL")
{
if (calendarActivities != null && adrCalActivities != null)
{
foreach (var cal in calendarActivities)
{
foreach (var adrCal in adrCalActivities)
{
if (cal.CalendarItemID == adrCal.CalendarItemID)
{
var adrCase = FileMaintenanceBusiness.Instance.GetADRMasterInfobyKeyword(adrCal.CaseNo, "CaseNo");
//LGF 08012011 ADR-59: add case coordinator - add CaseCoordinatorFilter
if (adrCase != null && CaseCoordinatorFilter(caseCoordinatorID, adrCase.CaseNo))
{
adrCase.ProcCode = _selectedProcCode;
adrCase.ProcDateString = cal.ProcDate.ToShortDateString();
_adrMasterList.Add(adrCase);
}
}
}
}
}
}
else
{
if (otherActivities != null && adrOtherActivities != null)
{
foreach (var otherActivity in otherActivities)
{
foreach (var adrotherActivity in adrOtherActivities)
{
if (otherActivity.ActivityID == adrotherActivity.ActivityID)
{
var adrCase = FileMaintenanceBusiness.Instance.GetADRMasterInfobyKeyword(adrotherActivity.CaseNo, "CaseNo");
//LGF 08012011 ADR-59: add case coordinator - add CaseCoordinatorFilter
if (adrCase != null && CaseCoordinatorFilter(caseCoordinatorID, adrCase.CaseNo))
{
adrCase.ProcCode = _selectedProcCode;
adrCase.ProcDateString = otherActivity.ProcDate.ToShortDateString();
_adrMasterList.Add(adrCase);
}
}
}
}
}
}
GeneratePrintReport();
}
That is happening because of internal identity map pattern implementation. You can never have attached two entity instances with the same entity key to the same context. You must simply call Detach once you load the entity.
context.Detach(entity);
Or you can try to load entities as non tracked (I'm not sure if it solves this problem):
context.YourEntitySet.MergeOption = MergeOption.NoTracking;
// Now run the query from YourEntitySet
Anyway it is odd that you want two instances of the same entity with different values. You should use separate non entity object for your "report" and make projections to that object. You would not have to deal with this problem at all.