Object with the same key already exists in ObjectStateManager - asp.net-mvc

I am trying to implement the following code but I keep getting the following error.
An object with the same key already exists in the ObjectStateManager. The existing object is in the Unchanged state. An object can only be added to the ObjectStateManager again if it is in the added state.
Function Create(lkmeasure As LkMeasure, ByVal oForm As FormCollection) As ActionResult
Dim ObjectiveList As New List(Of String)
Try
If ModelState.IsValid Then
If Not DirectCast(Session("LoggedInUser"), SecurityUser).SecurityRole.RoleName.ToLower.Equals(cCommon.UserRole.Administrator.ToString.ToLower()) Then
lkmeasure.AgencyID = DirectCast(Session("LoggedInUser"), SecurityUser).AgencyID
End If
lkmeasure.StatusID = Convert.ToInt16(oForm("MeasureStatus").ToString())
If Not oForm("PerformanceObjectives") Is Nothing AndAlso oForm("PerformanceObjectives").Length > 0 Then
'If Convert.ToInt16(oForm("PerformanceObjectives").ToString()).Equals(0) Then
' lkmeasure.ObjectiveID = 0
'Else
'lkmeasure.ObjectiveID = Convert.ToInt16(oForm("PerformanceObjectives").ToString())
ObjectiveList = oForm("PerformanceObjectives").ToString().Split(",").ToList()
'End If
End If
lkmeasure.MeasureCreateDate = DateTime.Now
lkmeasure.MeasureUpdateDate = DateTime.Now
'Dim lkMeasureObjList As New List(Of LkMeasure)
For Each obj In ObjectiveList
Dim lkmeasureobj As New LkMeasure
lkmeasureobj = lkmeasure
lkmeasureobj.MeasureCreateDate = DateTime.Now
lkmeasureobj.MeasureUpdateDate = DateTime.Now
lkmeasureobj.ObjectiveID = Convert.ToInt16(obj)
db.LkMeasures.AddObject(lkmeasureobj)
db.SaveChanges()
lkmeasureobj = Nothing
Next
Return RedirectToAction("Index")
End If
Call CreateViewBag()
Return View(lkmeasure)
Catch ex As Exception
Return Nothing
End Try
End Function
I have made the object nothing but still it says object is added.

If you want to add a new LkMeasure for each value in ObjectiveList then try something like the following:
For Each obj In ObjectiveList
Dim lkmeasureobj As New LkMeasure
' Copy values from your "prototype" lkmeasure instance
lkmeasureobj.AgencyID = lkmeasure.AgencyID
lkmeasureobj.StatusID = lkmeasure.StatusID
lkmeasureobj.MeasureCreateDate = DateTime.Now
lkmeasureobj.MeasureUpdateDate = DateTime.Now
lkmeasureobj.ObjectiveID = Convert.ToInt16(obj)
db.LkMeasures.AddObject(lkmeasureobj)
Next
' Only save once, outside of the loop
db.SaveChanges()

Related

How do you get the instance of the imported object after importing with django-import-export?

I'm trying to add objects to a related model after importing using django-import-export.
My Models
class Event(models.Model):
title = models.CharField(max_length=150)
class EventSession(models.Model):
event = models.ForeignKey(Event, on_delete=models.CASCADE, related_name="sessions")
start_date = models.DateTimeField()
end_date = models.DateTimeField()
My Import Data
id
start_date
start_time
minutes
sessions
9/1/21
10:00
60
2
9/8/21
10:00
60
3
My ModelResource Class
I am trying to override after_import_row to get the imported event and then create
the event sessions, but I don't know how to get the imported event.
class EventResource(resources.ModelResource):
start_date = fields.Field()
start_time = fields.Field()
def after_import_row(self, row, row_result, row_number=None, **kwargs):
""" After importing the row, get the saved event and save the event sessions."""
event = get_instance() # HOW TO GET THE INSTANCE????
start_datetime = timezone.make_aware(
datetime.combine(row["start_date"], row["start_time"])
)
end_datetime = start_datetime + timedelta(minutes=row["minutes"])
first_session = EventSession(
event=event,
start_date=start_datetime,
end_date=end_datetime,
)
first_session.save()
for _ in range(1, row["sessions"]):
# Sessions are always consecutive days
start_datetime = start_datetime + timedelta(days=1)
end_datetime = end_datetime + timedelta(days=1)
event_session = EventSession(
event=event,
start_date=start_datetime,
end_date=end_datetime,
)
event_session.save()
return super().after_import_row(
row, row_result, row_number=row_number, **kwargs
)
class Meta:
model = Event
fields = (
"id",
"title",
"start_date",
"start_time",
"sessions",
)
skip_unchanged = True
report_skipped = True
I figured out a solution. I can save the instance as an attribute of the EventResource object by overriding after_save_instance().
def after_save_instance(self, instance, using_transactions, dry_run):
self.instance = instance
return super().after_save_instance(instance, using_transactions, dry_run)
Then in after_import_row(), I use:
event = self.instance
You can also get hold of the instance id as follows:
def after_import_row(self, row, row_result, row_number=None, **kwargs):
print(row_result.object_id)
Obviously you can then load the object if required.
An alternative is to override after_import(). In this case, the result object passed to the method contains rows, which is a list of all imported rows.
def after_import(self, dataset, result, using_transactions, dry_run, **kwargs):
for row_result in result:
print(row_result.object_id)

Adding objects to array on Lua

First of all I'm new on lua, I'm trying to implement a simple shopping cart as an object oriented exercise.
So I defined a Cart Object which stores several items objects
Cart = {
items = {},
discount = 0
}
function Cart:new(discount)
local object = {}
setmetatable(object, {__index = self})
self.discount = discount
return object
end
function Cart:addItem(item)
table.insert(self.items, item)
end
function Cart:GetTotal()
local total = 0
for i = 1, #self.items do
total = total + self.items[i]:GetPrice()
end
return total - self.discount
end
Each Item has the responsibility of calculate their price:
Item = {
units = 0,
pricePerUnit = 5,
name = ""
}
function Item:new(units, pricePerUnit, name)
local object = {}
setmetatable(object, {__index = self})
self.units = units
self.pricePerUnit = pricePerUnit
self.name = name
return object
end
function Item:GetPrice()
return self.units * self.pricePerUnit
end
But when I create the object and add items I get 60 as result, When I debugged the script I found that all the elements of the table are identical as if they were overwritten, could someone explain to me why and how can it be solved? Thanks in advance.
local shoppingCart = Cart:new(0)
shoppingCart:addItem(Item:new(1, 10, "Oranges"))
shoppingCart:addItem(Item:new(1, 15, "lemons"))
shoppingCart:addItem(Item:new(1, 20, "Strawberries"))
print(shoppingCart:GetTotal())
Cart:new and Item:new are meant to create new objects, therefore you call them on the classes themselves rather than on instances. That means the self that gets passed to those methods is those classes.
In both of those methods, you create an object table to become the new object, so you need to set the fields on that object, instead of modifying the class, eg, object.discount = discount.

XAF web column grouping

if anyone has work with eXpressApp Framework (XAF)
I'm trying to group the listView by either one or two columns in the collection, Web module without luck, thanks in advance
Private Sub SCA_ViewBy_Execute(sender As Object, e As SingleChoiceActionExecuteEventArgs) Handles SCA_ViewBy.Execute
If SCA_ViewBy.SelectedIndex = 0 Then
Dim listEditor As GridListEditor = TryCast((CType(View, ListView)).Editor, GridListEditor)
If listEditor IsNot Nothing Then
Dim gridView As GridView = listEditor.GridView
gridView.BeginSort()
Try
gridView.ClearGrouping()
gridView.Columns("Division").GroupIndex = 0
gridView.Columns("SubDivision").GroupIndex = -1
Finally
gridView.EndSort()
End Try
End If
ElseIf SCA_ViewBy.SelectedIndex = 1 Then
Dim listEditor As GridListEditor = TryCast((CType(View, ListView)).Editor, GridListEditor)
If listEditor IsNot Nothing Then
Dim gridView As GridView = listEditor.GridView
gridView.BeginSort()
Try
gridView.ClearGrouping()
gridView.Columns("Division").GroupIndex = 0
gridView.Columns("SubDivision").GroupIndex = 1
Finally
gridView.EndSort()
End Try
End If
End If
End Sub
Thanks, I found a solution that works
Private Sub SCA_ViewBy_Execute(sender As Object, e As SingleChoiceActionExecuteEventArgs) Handles SCA_ViewBy.Execute
If SCA_ViewBy.SelectedIndex = 0 Then
' Dim listEditor As GridListEditor = TryCast((CType(View, ListView)).Editor, GridListEditor)
' If listEditor IsNot Nothing Then
' Dim gridView As GridView = listEditor.GridView
' gridView.BeginSort()
' Try
' gridView.ClearGrouping()
' gridView.Columns("Division").GroupIndex = 0
' gridView.Columns("SubDivision").GroupIndex = -1
' Finally
' gridView.EndSort()
' End Try
' End If
Dim listEditor1 As ASPxGridListEditor = TryCast((CType(View, ListView)).Editor, ASPxGridListEditor)
If listEditor1 IsNot Nothing Then
Dim gridView As ASPxGridView = CType(listEditor1.Grid, ASPxGridView)
gridView.ClientInstanceName = View.Id
Dim divisionColumns As GridViewDataColumn = TryCast(gridView.Columns("Division"), GridViewDataColumn)
'Dim subdivisionColumns As GridViewDataColumn = TryCast(gridView.Columns("SubDivision"), GridViewDataColumn)
If divisionColumns IsNot Nothing Then
'detailsColumns.DataItemTemplate = New UpDownButtonsTemplate()
gridView.ClearSort()
gridView.SortBy(divisionColumns, DevExpress.Data.ColumnSortOrder.Ascending)
gridView.GroupBy(divisionColumns, 0)
gridView.ExpandAll()
End If
End If
ElseIf SCA_ViewBy.SelectedIndex = 1 Then
Dim listEditor1 As ASPxGridListEditor = TryCast((CType(View, ListView)).Editor, ASPxGridListEditor)
If listEditor1 IsNot Nothing Then
Dim gridView As ASPxGridView = CType(listEditor1.Grid, ASPxGridView)
gridView.ClientInstanceName = View.Id
Dim divisionColumns As GridViewDataColumn = TryCast(gridView.Columns("Division"), GridViewDataColumn)
Dim subdivisionColumns As GridViewDataColumn = TryCast(gridView.Columns("SubDivision"), GridViewDataColumn)
If divisionColumns IsNot Nothing Then
'detailsColumns.DataItemTemplate = New UpDownButtonsTemplate()
gridView.ClearSort()
gridView.SortBy(divisionColumns, DevExpress.Data.ColumnSortOrder.Ascending)
gridView.GroupBy(divisionColumns, 0)
gridView.GroupBy(subdivisionColumns, 1)
gridView.ExpandAll()
End If
End If
Else
End If
End Sub

dao recordset updating the wrong record

I'm trying to have a form usable for both creating a new record or updating another. Currently it is doing it through the value of a textbox (new or edit). The structure works fine, but for some reason, when it is performing the edit function, it is saving changes to the wrong record. For instance, if I am editing record 1027, when i submit it, it'll update record 1073. Its consistent, it'll always update the same, wrong record. Edit 1000, it'll update 1073; if i update 1081, it'll update 1073, and so on. Is there a way to specify which record it should be editing? yes, the record number is the primary key/id. Heres the code:
Private Sub btnSubmit_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strTable As String
Dim strField As String
Dim ID As Long
Dim newID As Long
strTable = "record_holdData"
Set db = CurrentDb
Set rs = db.OpenRecordset(strTable)
'button has 2 modes
If txtMode.Value = "NEW" Then
With rs
.AddNew
.Fields("PO_no") = txtPONum
.Fields("prodSupervisor") = cboProdSup
.Fields("qaSupervisor") = cboQASup
.Fields("labTech") = cboLabTech
.Fields("flavor") = cboFlavor
.Fields("lineNumber") = cboLineNumber
.Fields("container") = cboContainer
.Fields("package") = cboPackage
.Fields("holdQty") = txtQty
.Fields("productionDate") = txtProdDate
.Fields("dateCode") = txtDatecode
.Fields("component") = cboComponent
.Fields("nonconformance") = cboDiscrepancy
.Fields("foundDuring") = cboFoundAt
.Fields("responsibility") = cboRespCode
.Fields("comments") = txtDescription
.Fields("rootCause") = txtRootCause
.Fields("holdStatus") = 1
.Fields("dateOpened") = Now()
.Update
.Bookmark = .LastModified
newID = !ID
End With
MsgBox ("Hold information saved!")
btnPrintTag.Enabled = True
DoCmd.OpenReport "Holdtag", acViewPreview, , "[ID] = " & newID
DoCmd.Close
ElseIf txtMode.Value = "EDIT" Then
'do editing stuff
With rs
.Edit
.Fields("PO_no") = txtPONum
.Fields("prodSupervisor") = cboProdSup
.Fields("qaSupervisor") = cboQASup
.Fields("labTech") = cboLabTech
.Fields("flavor") = cboFlavor
.Fields("lineNumber") = cboLineNumber
.Fields("container") = cboContainer
.Fields("package") = cboPackage
.Fields("holdQty") = txtQty
.Fields("productionDate") = txtProdDate
.Fields("dateCode") = txtDatecode
.Fields("component") = cboComponent
.Fields("nonconformance") = cboDiscrepancy
.Fields("foundDuring") = cboFoundAt
.Fields("responsibility") = cboRespCode
.Fields("comments") = txtDescription
.Fields("rootCause") = txtRootCause
.Fields("lastEditDate") = Now()
.Update
End With
MsgBox ("Information Updated")
End If
End Sub
Sorry i caught it. Problem was I was basically redefining the recordset each time the subroutine was called. I changed the second block to the following:
ElseIf txtMode.Value = "EDIT" Then
'do editing stuff
Set rs = db.OpenRecordset("SELECT * FROM record_holdData WHERE ID=" & txtID)
With rs
.Edit
.Fields("PO_no") = txtPONum
.Fields("prodSupervisor") = cboProdSup
.Fields("qaSupervisor") = cboQASup
.Fields("labTech") = cboLabTech
.Fields("flavor") = cboFlavor
.Fields("lineNumber") = cboLineNumber
.Fields("container") = cboContainer
.Fields("package") = cboPackage
.Fields("holdQty") = txtQty
.Fields("productionDate") = txtProdDate
.Fields("dateCode") = txtDatecode
.Fields("component") = cboComponent
.Fields("nonconformance") = cboDiscrepancy
.Fields("foundDuring") = cboFoundAt
.Fields("responsibility") = cboRespCode
.Fields("comments") = txtDescription
.Fields("rootCause") = txtRootCause
.Fields("lastEditDate") = Now()
.Update
End With

Grails error: No such property: it for class:

Below is my code.
Here I am getting an error which is 'No such property: it for class: emp.EmployeeController'.
I think I am doing something wrong here.
Any advice??
def list ={
def id=params.id
def results
String employee="SELECT empName, empDate, empNo from employee where empId='id'"
String referrer="SELECT empName, empDate, empNo from referer where empId='id'"
def employeeInstanceList = new ArrayList<Employee>()
Sql sql = new Sql(dataSource)
def joining=null
joining = sql.rows( "select joining from employee_dates")
if (joining!=null)
results = sql.eachRow(employee)
employeeInstanceList=getCalculatedEmployeeData(results)
/*{
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee
}*/
else
results = sql.rows (currentDaySql)
employeeInstanceList=getCalculatedEmployeeData(results)
/*{
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee }*/
}
[employeeInstanceList: [employeeInstanceList: employeeInstanceTotal: Employee.count()]
}
def getCalculatedImpactData(def results){
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee }*/
return [employeeInstanceList: employeeInstanceList]
}
Thanks,
Meghana
i would second leebutts answer... but just a pointer, the usage of the it keyword is usually confined to closures... so instead of doing this in java:
List l = [];
for (Iterator i = l.iterator(); i.hasNext(); ) {
...do something adressing List l at position i...
}
you could do this in groovy / grails:
list.each { it ->
...do something with each object in the list (it)...
}
but you should really read up on groovy closures at http://groovy.codehaus.org/Closures
There is so much wrong with that code, I don't know where to start...
But to avoid getting more down votes I have tried :)
I tried to copy your code into an IDE and try and work out what you are trying to achieve but couldn't.
This is as close as I could get it:
def list = {
def id = parmas.id
def results
String employee = "SELECT empName, empDate, empNo from employe"
def employeeInstanceList
Sql sql = new Sql(dataSource)
def joining = sql.rows("select joining from employee_dates")
if (joining != null) {
results = sql.eachRow(employee)
employeeInstanceList = getCalculatedEmployeeData(results)
}
else {
results = sql.rows(currentDaySql)
employeeInstanceList = getCalculatedEmployeeData(results)
}
[employeeInstanceList: employeeInstanceList, employeeInstanceTotal: Employee.count()]
}
def getCalculatedImpactData(def results) {
def employeeInstanceList = new ArrayList<Employee>()
results.each { it ->
def employee = new Employee()
employee.empName = it.empName
employee.empNo = it.empNo
employee.empDate = it.EmpDate
employeeInstanceList.add(employee)
}
return employeeInstanceList
}
but it is still referring to a variable currentDaySql which doesn't exist and I'm not sure what you're trying to do with the 'joining' result.
You really need to read up on Groovy basics.
The block of code where the error occurs is probably:
def getCalculatedImpactData(def results){
def employee = new Employee()
employee.setempName it.empName
employee.setEmpNo it.empNo
employee.setEmpDate it.EmpDate
employeeInstanceList.add employee
return [employeeInstanceList: employeeInstanceList]
}
it is not defined anywhere (hint: the compilation error told you this). Like Sebastian said, it is typically used in closures; what you've defined here is a function. Presumably you wanted to use results (or something) instead of it here.
I'm assuming that some of the things in your code (e.g. comment opening/closing) weren't in there and were added between when you saw the error and when you posted the code. Otherwise you'd get other errors.

Resources