Removing relationship 1-to-many between objects requires removing on both sides - asp.net

I am using Code First EF. I have following code in my project
If String.IsNullOrEmpty(ddlProductionLocation.SelectedValue) Then
CurrentUser.ProductionLocation = Nothing
Else
CurrentUser.ProductionLocation = ProductionLocationRepository.Find(DataContext, Integer.Parse(ddlProductionLocation.SelectedValue))
End If
ddlProductionLocation is simply dropdown, CurrentUser is plain EF object, ProductionLocationRepository is boring class which provides me with access to database indirectly (returns plain EF object too).
User and ProductionLocation have 1-to-n relationship.
This did not work correctly for removing relationship as after setting ProductionLocation to nothing, it still contained original value. It worked randomly in few cases (during debugging etc).
Base on that I have realized, that problem is second part of relationship. I have changed code to this:
If String.IsNullOrEmpty(ddlProductionLocation.SelectedValue) Then
If CurrentUser.ProductionLocation IsNot Nothing Then
CurrentUser.ProductionLocation.Users.Remove(CurrentUser)
End If
CurrentUser.ProductionLocation = Nothing
Else
CurrentUser.ProductionLocation = ProductionLocationRepository.Find(DataContext, Integer.Parse(ddlProductionLocation.SelectedValue))
End If
MY QUESTION:
This works, but I believe this is not correct solution. Or is it? Or do i really have to remove both sides of relationship at all cases?
Thaks
EDIT:
Final solution is:
If String.IsNullOrEmpty(ddlProductionLocation.SelectedValue) Then
Dim pl = CurrentUser.ProductionLocation 'HACK for loading Product Location before setting it
CurrentUser.ProductionLocation = Nothing
Else
CurrentUser.ProductionLocation = ProductionLocationRepository.Find(DataContext, Integer.Parse(ddlProductionLocation.SelectedValue))
End If
Not nice, but works.

Related

VS 2017 / ASP.net - Global functions not being recognized

I made the jump from VS 2010 (VB) all the way to VS 2017, and that may have been a mistake. I've already been slowed down with bugs, which I have reported. My latest concern is about accessing a global functions class that I have never had a problem with in VS 2010. I have reported it and it is in triage, but I wanted to make sure that something hasn't changed in the versions since 2010, hoping someone here can tell me.
Essentially what happens is that the global class, no matter how it is configured, is not recognized by any other class. Including a reference in a form class causes the IDE to tag it as an error. For example, the code in the GlobalFunctions.vb document:
Public Class GlobalFunctions
Public Function DecodeBase64(strEncoded As String) As String
Dim byt As Byte() = Convert.FromBase64String(strEncoded)
Return (System.Text.ASCIIEncoding.ASCII.GetString(byt))
End Function
Public Function EncodeBase64(strUnencoded As String) As String
Dim byt As Byte() = System.Text.Encoding.UTF8.GetBytes(strUnencoded)
Return (Convert.ToBase64String(byt))
End Function
End Class
and the calling methods from a form page:
If elemSetting.Attributes("name").Value = "LoginName" Then
Session("MailLoginName") = globalfunctions.DecodeBase64(elemSetting.Attributes("value").Value)
End If
If elemSetting.Attributes("name").Value = "LoginPass" Then
Session("MailLoginPass") = globalfunctions.DecodeBase64(elemSetting.Attributes("value").Value)
End If
Here the errors are being highlighted in the IDE:
And the error messages in the error list:
Understand, too, that I have tried as many variations of declarations as I can think of, such as "Public Shared Function," making the calling sub Shared, defining the global functions document as a Class or a Module, etc. Nothing works.
I've also tried placing the GlobalFunctions.vb class in the project's root directory and in a directory named App_Code, as was suggested in some blog posts around the net.
And since I have had no trouble like this with VS 2010, I assume it's a bug in 2017, which, as I said, I have reported. But I wanted to check with better minds than my own to see if I have overlooked something that may have changed somewhere between 2010 and 2017.
Can someone tell me if I am doing something wrong? Or maybe reaffirm for me that this is, indeed, a bug?
Thanks!
Try to delete and recreate your GlobalFunction.vb as maybe by renaming it in the past it didn't correctly correct everywhere in the project.
I think this is normal. You are using a Class and not a Module so you would need to declare a new instance either call like this:
Dim Globaler As New GlobalFunctions
If elemSetting.Attributes("name").Value = "LoginName" Then
Session("MailLoginName") = Globaler.DecodeBase64(elemSetting.Attributes("value").Value)
End If
If elemSetting.Attributes("name").Value = "LoginPass" Then
Session("MailLoginPass") = Globaler.DecodeBase64(elemSetting.Attributes("value").Value)
End If
Or use a Module and you wont need to declare a new instance.
Also if it still can't be accessed you should check the fact that maybe you just included the file to the solution without including it to the project
To Add new class:
Solution Explorer
Right Click your Project Name (above My Project)
Add
Class

Controls and null reference exception

I'm aware that the NullReferenceException is pretty much the equivalent to the check engine light on a car but with this particular case I can't seem to pinpoint why its not working properly, I've never really messed with controls so I'm a bit unfamiliar in with the technicalities of it. What I have works, but I keep getting the exception when I run a trycatch around it. Here is what I have.
Dim TypeControl As Control
TypeControl = MaterialHeader_Edit1.FindControl("cboType")
DBTable = MaterialStuff.GetMaterial(ID)
Using DBTable
If DBTable.Rows.Count > 0 Then
Try
CType(TypeControl, DropDownList).SelectedItem.Text = (DBTable.Rows(0).Item("MaterialTypeDescription").ToString)
Catch ex As NullReferenceException
trace.runAllErrorLogging(ex.ToString)
End Try
End If
A NullReferenceException doesn't have anything to do with "controls" specifically. It's just an indication that your code assumes an object exists when at runtime it doesn't exist. For example, if you do this:
TypeControl = MaterialHeader_Edit1.FindControl("cboType")
CType(TypeControl, DropDownList).SelectedItem.Text = ...
Then your code assumes that TypeControl has a value on the second line. If it doesn't, trying to use .SelectedItem will fail because TypeControl is null. So you're assuming that .FindControl() actually found something. It doesn't make that guarantee implicitly.
Instead of making this assumption, you should verify:
TypeControl = MaterialHeader_Edit1.FindControl("cboType")
If TypeControl Is Not Nothing Then
CType(TypeControl, DropDownList).SelectedItem.Text = ...
End If
That way the code only executes if there's a value that it can use. You can add an Else to handle the condition where no value is found. (Display an error? Log the error? Silently continue? It's up to you how the condition should be handled.)
There are two possible problems here:
1 - Does FindControl actually find the control you seek? Add a check in to make sure you are actually finding it:
Dim TypeControl As Control
TypeControl = MaterialHeader_Edit1.FindControl("cboType")
If TypeControl Is Nothing Then Debug.Writeline("Could not find control")
2 - The SelectedItem of the control could also be Nothing so you may need to add a check here:
Dim ddl = CType(TypeControl, DropDownList)
If ddl.SelectedItem Is Nothing Then Debug.Writeline("Could not find selectedItem")

Get property value of control in a dynamically created usercontrol

I'm having trouble recovering a reference to a user control that is created dynamically so I can get the values of its properties or child controls.
I have a custom control called BookingObject.ascx which resides in App_Code.
I can create the controls programmatically without a problem but, later on, when I try to get a reference to the control, in order to access its child controls values, I just keep getting null.
Heres some code:
Dim MainItem As BookingItem = TryCast(LoadControl(GetType(BookingItem), Nothing), BookingItem)
MainItem.ID = "Item_" & NumberOfControls.ToString() 'Item_0
Dim lblid As Label = MainItem.FindControl("lblID")
lblid.Text = (NumberOfControls + 1).ToString()
NewItemPH.Controls.Add(MainItem)
Me.NumberOfControls += 1
This works fine and I can set the labels value successfully.
However:
Dim MainItem As BookingItem = TryCast(Me.Page.FindControl("Item_0"), BookingItem)
Dim product_id As DropDownList = MainItem.FindControl("product_id")
I get a null reference exception when trying to FindControl("product_id") as MainItem is nothing.
I've been struggling with this issue for hours now and it's something I assumed would be simple. I'm sure i'm just missing something small.
Can anyone tell me what I'm doing wrong?
All help is appreciated.
UPDATE
Never mind, I was being stupid and searching Me.Page for the control when I should have been searching NewItemPH.
Thanks to the mystery person who gave me the clue and then deleted their comment minutes later.

asp.net VB Delete Multiple Rows in EF4

I'm struggling with deleting multiple rows. I'm learning and have managed new rows and edits but cant seem to nail delete. Can someone help please?
this is what I have:
If ViewState("QuoteGroupID") IsNot Nothing Then
Dim GQID As Integer = CInt(ViewState("QuoteGroupID"))
Using db As New quotingSystemDevEntities
Dim QuoteToDelete = (From q In db.QuotesGeneratedV2 Where q.QuoteGroupID = GQID Select q)
db.DeleteObject(QuoteToDelete)
db.SaveChanges()
End Using
End If
I'm getting the error "The object cannot be deleted because it was not found in the ObjectStateManager."
Thanks you for your time.
UPDATE
After much messing around I have figured it out. The info on the web was very difficult to make sense of so I went for the try everything until it works method... Might not be the perfect solution but it works better than the one that wasn't! Hopefully this info will help someone out:
If ViewState("QuoteGroupID") IsNot Nothing Then
Dim GQID As Integer = CInt(ViewState("QuoteGroupID"))
Using db As New quotingSystemDevEntities
Dim QuoteToDelete = (From q In db.QuotesGeneratedV2 Where q.QuoteGroupID = GQID Select q)
For Each item In QuoteToDelete
db.Detach(item)
db.Attach(item)
db.DeleteObject(item)
Next
db.SaveChanges()
End Using
End If
I think you missing ObjectContext.Attach Method. Try using that.
Also similar question can be found Entity Framework Delete Object Problem

Rails 3 ActiveRecord::Relation random associations behavior

I am currently having a strange issue with an application migrated from rails 2.3.8 to rails 3 (3.0.1, 3.0.2, 3.0.3).
At random moments associations behave strangely. In some cases, an associated object will return the Relation object, instead of the corresponding model. This seems to happen mostly on polymorphic associations. For example:
class A
belongs_to :b, :polymorphic => true
end
class B
has_many :a, :as => :source
end
When invoking "a.b" this will "sometimes" return the Relation object (causing a "undefined method ... for ActiveRecord::Relation" error to raise) and some other times it will return the correct B object.
When the relation object is returned, it may sometimes be "fixed" temporarily by restarting the server, but it will eventually show up again.
Another issue i get is that when "getting" associated objects, sometimes the required filters are not automatically applied (where element id = ...). this causes the query to return the first object in the table and not the correct associated object.
This is becoming a very frustrating issue, specially since i don't seem to find anyone else with this or similar issues.
All finder methods in the application have been migrated to the new rails form, but this strange behavior remains.
The current configuration being used is:
Ubuntu 10
nginx server
passenger (3.0.2)
rails (3.0.3)
ruby 1.9.2p0 (2010-08-18 revision 29036)
After digging a bit deeper into the Active Record code, my co-worker and I found that the belongs_to_association.rb and belongs_to_polymorphic_association.rb were still using the old finder methods in the "find_target" method.
We ran a couple tests by logging the resulting objects of this method from different queries and discovered the old finders were returning the ActiveRecord::Relation at random moments (loading the same object it would sometimes return the object and other times the Relation object).
We overrode the find_target method for these 2 classes in initializer files, changing the finders used there to the new rails3 format (klass.select(...).where(...), etc). This seems to have solved the issue.
The "has_many" association files are already using the new format, so these haven't caused any issues.
We applied these "fixes" to the rails 3.0.3 and hope that they will be resolved in future releases.
Here are our initializer files in case someone else bumps into this problem:
belongs_to_polymorphic_association.rb:
#initializers/belongs_to_polymorphic_association.rb
module ActiveRecord
# = Active Record Belongs To Polymorphic Association
module Associations
class BelongsToPolymorphicAssociation < AssociationProxy #:nodoc:
private
def find_target
return nil if association_class.nil?
target =
if #reflection.options[:conditions]
association_class.select(#reflection.options[:select]).where(conditions).where(:id => #owner[#reflection.primary_key_name]).includes(#reflection.options[:include]).first
else
association_class.select(#reflection.options[:select]).where(:id => #owner[#reflection.primary_key_name]).includes(#reflection.options[:include]).first
end
set_inverse_instance(target, #owner)
target
end
end
end
end
belongs_to_association.rb:
#initializers/belongs_to_association.rb
module ActiveRecord
# = Active Record Belongs To Associations
module Associations
class BelongsToAssociation < AssociationProxy #:nodoc:
private
def find_target
key_column = (#reflection.options[:primary_key]) ? #reflection.options[:primary_key].to_sym : :id
options = #reflection.options.dup
(options.keys - [:select, :include, :readonly]).each do |key|
options.delete key
end
options[:conditions] = conditions
the_target= #reflection.klass.select(options[:select]).where(key_column => #owner[#reflection.primary_key_name]).where(options[:conditions]).includes(options[:include]).readonly(options[:readonly]).order(options[:order]).first if #owner[#reflection.primary_key_name]
set_inverse_instance(the_target, #owner)
the_target
end
end
end
end
Hope this is useful for someome
Thanks for sharing this. The problem with associations gone. But I still had this issue even with straight "find" method.
#post = Post.find(params[:id)
#post.update_attributes...
will fail with ActiveRecord::Relation error. However
#post = Post.find_by_id(params[:id])
#post.update_attributes...
will work
Seems like strange lazy loading behaviour

Resources