deleting a record in linq to sql (vb.net) what is wrong with my code? - linq

I am getting the correct Employee Id in the VarEmpID variable. When I click on delete
It is giving me
Unable to cast object of type 'System.Data.Linq.DataQuery`1[my name space]' to type 'namespace'.
enter code here
Protected Sub radGrid1_DeleteCommand(ByVal source As Object, ByVal e As GridCommandEventArgs) Handles radGrid1.DeleteCommand
Dim VarEmpId As String = (CType(e.Item, GridDataItem)).OwnerTableView.DataKeyValues(e.Item.ItemIndex)("EmpId").ToString()
Using dc1 As New EmployeesDataClassesDataContext()
Dim EmployeeEntry = (From p In dc1.Employees
Where (p.EmpId = VarEmpId)
Select p)
dc1.Employees.DeleteOnSubmit(EmployeeEntry)
dc1.SubmitChanges()
Dim queryResults = (From queryItem In EmployeeEntry Select queryItem).ToList()
If queryResults.Any Then
radGrid1.DataSource = queryResults
radGrid1.DataBind()
End If
End Using
End Sub

dc1.Employees.DeleteOnSubmit(EmployeeEntry)
That method expects an Employee instance. Instead, you passed in an employee query.
Dim EmployeeEntry = ( query )
This is a query, not an entry. Consider calling Enumerable.First to get the first result of the query, and then deleting that.

Modified added Dim EmployeeEntry = (From p In dc1.Employees Where (p.EmpId = VarEmpId) Select p).singleorDefault() After that commented out the queryresults part and binded data again it solved my problem. – SmilingLily

Related

Retrieving Only Selected Field Using LINQ

i have a problems regarding on filtering my code in retrieving companyName from its table..when i query here is the result .. please see my code
Sub call_customers(ByVal dgv_customers As DataGridView)
Dim customers_name = From cust In dbcon.Customers _
Select cust.CustomerID, cust.CompanyName Order By CompanyName Ascending
dgv_customers.DataSource = customers_name
End Sub
the display is CustomerID and CompanyName.. yeah its true.. no problem with the code..
and if i only select cust.companyname the result is this ....like this code
Sub call_customers(ByVal dgv_customers As DataGridView)
Dim customers_name = From cust In dbcon.Customers _
Select cust.CompanyName
dgv_customers.DataSource = customers_name
End Sub
the output is this...
enter image description here
no display and it says length.. why? newbie in LINQ sir ..
please help..
Originally, you were giving the grid an object, and it was displaying each of the properties of that object.
Now that you are giving it a string, it is doing the same thing, but now, the only property on the string is the length,

Search multiple values in one column

How to select record based on multiple values search in one column using linq query.
like product id is "product1", "product2","product3" n number of values we have
You can use the .Contains method to check whether a value is within a list.
var values = new List<string>() { "Prod1", "Prod2", "Prod3" };
var query = context.Set<Product>().Where(x => values.Contains(x.Name));
You could use something like (this is VB.Net, change to C# if necessary)
Dim result = products.Where(Function(p) p.ID = "product1" Or p.ID = "product2" Or p.ID = "product3", ...)
Alternatively, you could pull it all back to the client and use .Contains, like so:
Dim materializedProducts = products.ToList()
Dim result = materializedProducts.Where(Function(p) {"product1", "product2", "{product3}", ...}.Contains(p.ID))
Going further still, you could create an extension method (generic, if that floats your boat) called IsIn or similar that allows you to swap the order of the collection and the search value:
<Extension()>
Public Function IsIn(Of T)(ByVal searchValue As T,
ByVal searchSet As IEnumerable(Of T))
Return searchset.Contains(searchValue)
End Sub
Dim materializedProducts = products.ToList()
Dim result = materializedProducts.Where(Function(p) p.ID.IsIn({"product1", "product2", "{product3}", ...}))

How to translate a part using CATscript in CATIA?

I working with CATscript in CATIA to create Macros. I am trying to create a CATscript to translate a feature in CATIA.
When I run the CATscript I Should select the feature that should be translated and and the feature will be translated.
But I am getting an runtime error Type mismatch:'part1.CreateReferenceFromObject'
I could not find the solution for this problem.
Looking forward for your help.
Thanks in Advance.
Sub CATMain()
Set partDocument1 = CATIA.ActiveDocument
Set part1 = partDocument1.Part
Set hybridShapeFactory1 = part1.HybridShapeFactory
Set hybridShapeDirection1 = hybridShapeFactory1.AddNewDirectionByCoord(1.000000, 0.000000, 0.000000)
Set hybridShapeTranslate1 = hybridShapeFactory1.AddNewEmptyTranslate()
Set UserSel = partDocument1.Selection
Dim type1(0)
type1(0) = "HybridShape"
'--------------------------------------
'Dim input As Object
input = UserSel.SelectElement2(type1, "select input.", False)
Set reference1 = part1.CreateReferenceFromObject(input)
hybridShapeTranslate1.ElemToTranslate = reference1
hybridShapeTranslate1.Direction = hybridShapeDirection1
hybridShapeTranslate1.DistanceValue = 1.000000
Set hybridBody2 = hybridBodies1.Item("Geometrical Set.3")
hybridBody2.AppendHybridShape hybridShapeTranslate1
part1.InWorkObject = hybridShapeTranslate1
part1.Update
End Sub
your problem is that you are trying to create a reference from a Selection object.
input = UserSel.SelectElement2(type1, "select input.", False)
This returns the type Selection. You can dig into the input and get the actual object that you select.
try:
Dim myReference as Reference
Dim myExpectedObject as HybridShape 'or use variant
Set mySelectedObject = input.Item2(1).Value 'this will grab the first item from the selection collection
set myReference = part1.CreateReferenceFromObject(mySelectedObject)
'continue the rest of your code
Also, you should always clear the selection before you use a user selection as a good habit.
UserSel.Clear 'call this before you call a SelectElement selection function

LINQ to SQL, Visual Basic - Listbox Receives the Query NOT the Result

Overview
This is a homework assignment using LINQ to SQL in a Visual Basic application. It is correct in most ways except that I have a partially broken result. Rather than adding the result of my second query to my listbox, my code adds a weird representation of the query itself. Below is a description of the DB, followed by my output (intended and actual), and finally my code. Please point me toward the broken concept so I can figure out what I am missing. Thanks much.
DB info
I am using two tables, called Members and Payments, from one DB. Members has a primary key called ID and also has the fields first_name and last_name. Payments has a foreign key called Members_Id, which is associated to the Member's primary key; Payments also has the payment values under the column Payments.
Output should be like this
Member name = John Smith
$48.00, 10/20/2005
$44.00, 3/11/2006
But is this instead
Member name = SELECT ([t0].[First_Name] + #p1) + [t0].[Last_Name]
AS [value]FROM[dbo].[Members] AS [t0].[ID] = #p0
$48.00, 10/20/2005
$44.00, 3/11/2006
My VB Code
Public Class FormPaymentsGroup
Private db As New KarateClassesDataContext
Private Sub FormPaymentsGroup_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Me.PaymentsTableAdapter.Fill(Me.KarateDataSet.Payments)
'Group payments by Member_ID (FKey) in the Payments table. (Working fine)
Dim IdQuery = From aMember In db.Payments
Group aMember By aMember.Member_Id
Into MemberPayments = Group
For Each memberID In IdQuery
' Use the passed member_Id to target the row in the Members table and return the first_name & last_name.
' PROBLEM: This only seems to be returning the query itself; not the result.
Dim currMemberID = memberID.Member_Id
Dim nameQuery = From aName In db.Members
Where aName.ID = currMemberID
Select aName.First_Name + " " + aName.Last_Name
Dim currName = nameQuery.ToString ' Load the query result into a portable variable.
LbxMemberPayments.Items.Add("Member name = " & currName) ' PROBLEM: This is where the name SHOULD BE posted to the listbox.
' This is bound to the Members table but directs it based on the above IdQuery.
For Each enteredPayment In memberID.MemberPayments
LbxMemberPayments.Items.Add(vbTab & FormatCurrency(enteredPayment.Amount) & ", " & enteredPayment.Payment_Date)
Next
LbxMemberPayments.Items.Add(vbCr) ' Carriage return formatting
Next
End Sub
End Class
change
Dim currName = nameQuery.ToString
to
Dim currName = nameQuery.FirstOrDefault

Accessing anonymous types returned via a dynamic link query

I have been trying to access the data returned from a dynamic linq query as an anonymous type. The advice I have found suggests that I should create a custom type and use it in the Select clause with the new keyword. I was directed to the followed Question for a code example:
System.LINQ.Dynamic: Select(" new (...)") into a List<T> (or any other enumerable collection of <T>)
This was indeed an excellent example which I incorporated into my code (which is VB so I had to do some translation).
My code compiles fine but When I run it , I get the error following error:
"Value cannot be null. Parameter name: member" at the following line from the example:
bindings[i] = Expression.Bind(type.GetProperty(properties[i].Name), expressions[i]);
This seems to be linked to expressions(i), which correctly contains two items as I am returning two fields from the database table. properties(i) holds the name of those two fields correctly. Any ideas as to what the value for member is supposed to be and where it should be found? Is it something from the database?
The where clause of this query works and when I run it as an anonymous type it brings back records (or rather two fields from records). The returned fields contain data not nulls.
Here is my VB version of the code from the example provided in the earlier Question. I have bolded or ** the line where the error occurs. Any ideas as to what is causing this?
Much appreciated.
Function ParseNew() As Expression
NextToken()
ValidateToken(TokenId.OpenParen, Res.OpenParenExpected)
NextToken()
Dim properties As New List(Of DynamicProperty)()
Dim expressions As New List(Of Expression)()
Do
Dim exprPos = tokenVal.pos
Dim expr = ParseExpression()
Dim propName As String
If TokenIdentifierIs("as") Then
NextToken()
propName = GetIdentifier()
NextToken()
Else
Dim [me] As MemberExpression = TryCast(expr, MemberExpression)
If [me] Is Nothing Then Throw ParseError(exprPos, Res.MissingAsClause)
propName = [me].Member.Name
End If
expressions.Add(expr)
properties.Add(New DynamicProperty(propName, expr.Type))
If tokenVal.id <> TokenId.Comma Then Exit Do
NextToken()
Loop
ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected)
NextToken()
'CODE added to support strongly-typed returns
Dim type As Type = If(newResultType, DynamicExpression.CreateClass(properties))
Dim bindings(properties.Count - 1) As MemberBinding
For i As Integer = 0 To bindings.Length - 1
**bindings(i) = Expression.Bind(type.GetProperty(properties(i).Name), expressions(i))**
Next
Return Expression.MemberInit(Expression.[New](type), bindings)
End Function

Resources