Multi Models in View (Anon Conversion Error) - vb.net

I am really struggling with getting two tables I have joined to show in a view (I just want to show the customer name which comes from the customer tables and the bill status from the bill table - both of which are joint on a CustomerId primary key). I spent ages researching this and came to the conclusion of creating another model just for this view which I did however in my controller when I try and use the following:
Function ShowAll() As ViewResult
Dim BillQuery = From d In db.Bills
Join c In db.Customers On d.CustomerId Equals c.CustomerId
Select c.CustSurname, d.BillStatus
Dim BillList As List(Of BillView) = BillQuery.ToList()
Return View(BillList)
End Function
I get an error:
Value of type 'System.Collections.Generic.List(Of )' cannot be converted to 'System.Collections.Generic.List(Of Laundry.BillView)'
Here are my Bill and BillView models:
Imports System.Data.Entity
Imports System.ComponentModel.DataAnnotations
Public Class Bill
'Key
Public Property BillId() As Integer
'Others
<Required()>
<Display(Name:="Customer ID")>
Public Property CustomerId() As String
<Required()>
<Display(Name:="Bill Status")>
Public Property BillStatus() As String
End Class
Public Class BillView
Public Property CustSurname() As String
Public Property BillStatus() As String
End Class
And Customer Model:
Imports System.Data.Entity
Imports System.ComponentModel.DataAnnotations
Public Class Customer
'Key
Public Property CustomerId() As Integer
'Others
<Display(Name:="Group ID")>
Public Property GroupId() As Integer
<Required()>
<Display(Name:="Firstname")>
Public Property CustFirstname() As String
<Required()>
<Display(Name:="Surname")>
Public Property CustSurname() As String
<Display(Name:="Email")>
Public Property CustEmail() As String
<Display(Name:="Cellphone")>
Public Property CustCellphone() As String
<Display(Name:="Address")>
Public Property CustAddress() As String
<Required()>
<Display(Name:="Status")>
Public Property CustStatus() As String
<Required()>
<Display(Name:="Account Balance")>
Public Property AccBalance() As Double
<Required()>
<Display(Name:="Loyalty Ammount")>
Public Property LoyaltyAmount() As Double
<Required()>
<Display(Name:="Customer Discount")>
Public Property PersonalDiscount() As Double
End Class

It looks like your first LINQ query is returning an anonymous type which can't then be cast to List(Of BillView). Try the following code to return a collection of BillView models prior to the cast (note the added syntax Select New BillView With {}).
Function ShowAll() As ViewResult
Dim BillQuery = From d In db.Bills
Join c In db.Customers On d.CustomerId Equals c.CustomerId
Select New BillView With {.CustSurname = c.CustSurname, .BillStatus = d.BillStatus}
Dim BillList As List(Of BillView) = BillQuery.ToList()
Return View(BillList)
End Function

Related

SQL query works in navicat but not work in vb.net

I am trying to get data using GROUP BY statement:
SELECT nama_penerbit
FROM DigitalBook.digitalbook.ebook
ORDER BY nama_penerbit
and store this value.
Using navicat
but did not get the value when I try to get in controller in VB.NET:
<Route("api/Ebooks/GetAllPenerbit")>
<HttpGet>
Function GetAllPenerbit() As Results.JsonResult(Of List(Of ebook))
Dim kategoriEbookRepository As New EbookReposity
Dim d = kategoriEbookRepository.PenerbitEbookRepository()
Return Json(d)
End Function
This is my model class:
Public Function PenerbitEbookRepository() As List(Of ebook)
Dim sql = "Select nama_penerbit From Digitalbook.digitalbook.ebook Group by nama_penerbit"
Dim datas As New List(Of ebook)
Try
datas = db.Database.SqlQuery(Of ebook)(sql).ToList
Catch ex As Exception
End Try
Return datas
End Function
This is my class
<Table("digitalbook.ebook")>
Partial Public Class ebook
<Key>
<StringLength(50)>
Public Property id_ebook As String
<StringLength(500)>
Public Property judul As String
Public Property id_kategori_ebook As Guid?
<StringLength(255)>
Public Property pengarang As String
<StringLength(255)>
Public Property nama_penerbit As String
End Class
i created a new class with the same property, then i used it on controller and model, it works fine
This is my new class
Partial Public Class getebook
Public Property id_ebook As String
Public Property judul As String
Public Property id_kategori_ebook As Guid?
Public Property pengarang As String
Public Property nama_penerbit As String
End Class
My Controller
<Route("api/Ebooks/GetAllPenerbit")>
<HttpGet>
Function GetAllPenerbit() As Results.JsonResult(Of List(Of getebook))
Dim kategoriEbookRepository As New EbookReposity
Dim d = kategoriEbookRepository.PenerbitEbookRepository()
Return Json(d)
End Function
My Model
Public Function PenerbitEbookRepository() As List(Of getebook)
Dim sql = "Select Distinct nama_penerbit From Digitalbook.digitalbook.ebook"
Dim datas As New List(Of getebook)
Try
datas = db.Database.SqlQuery(Of getebook)(sql).ToList
Catch ex As Exception
End Try
Return datas
End Function

How To Access Data In A Class Within A Class With VB.NET

I am relatively new to VB.NET Classes that define data structures. Also the terminology is a little unfamiliar.
I have defined the following Class structures:
Public Class CatalogInfoDef
Public CatalogName As String
Public CatalogYear As String
Public CatalogNumber As String
End Class
Public Class ParameterDef
Public Country As String
Public GeographicArea As String
Public Catalogs As List(Of CatalogInfoDef)
Public Class IssueDate
Public Month As String
Public Day As String
Public Year As String
End Class
Public Class Size
Public Width As String
Public Height As String
End Class
Public Printer As String
Public SearchKeywords As List(Of String)
Public Class OtherInfo
Public Condition As String
Public PrintMethod As String
End Class
End Class
In the Main Form I have the definition: Private ParameterInfo as New ParameterDef
I am able to insert data into the fields that are in the main Class, Country, etc.. However, I am having problems inserting data into fields such as: IssueDate (Month, Day, Year).
How do I access the data in these Class fields? Am I missing some parameter? Is there a better way to define ParameterDef?
What you're doing is defining classes within a class when it sounds like you want to define a property of a custom class. Something more along the lines of:
Public Class ParameterDef
Public Property Country As String
Public Property GeographicArea As String
Public Property Catalogs As List(Of CatalogInfoDef)
Public Property IssueDate As DateTime
Public Property Size As Size
Public Property Printer As String
Public Property SearchKeywords As List(Of String)
Public Property OtherInfo As OtherInfo
End Class
Public Class OtherInfo
Public Condition As String
Public PrintMethod As String
End Class
Then when you go to set the properties it would be:
Private ParameterInfo as New ParameterDef() With {
.Country = "...",
.GeographicArea = "..."
.Catalogs = New CatalogInfoDef() With {
.CatalogName = "...",
.CatalogYear = "...",
.CatalogNumber = "..."
},
.IssueDate = New DateTime(year, month, day) ' replace with actual values
.Size = New Size(width, height) ' replace with actual values
.Printer = "...",
.SearchKeywords = New List(Of String)(),
.OtherInfo = New OtherInfo() With {
.Condition = "...",
.PrintMethod = "..."
}
}
Also, notice how I removed your custom Date and Size class. This is because those classes already exist in the System and System.Drawing namespaces respectively.

Refer to a Class from within a With VB.net

I have called clientdetails which I wish to return as a whole to the JSONConvert Method to Serialize for JSON.
I have created a Class that has the Property Types I require (TextA,TextB) etc.
I can refer to both TransactionCount and TransactionType because they are part of ClientDetails, however when I try to refer to TextA of Transactions it states that TextA is not a member of ClientDetails - this I know which is why I explicitly state .Transactions.TextA.
If I declare Transactions separate under a new variable then I am able to refer to them however I need them to all be declared under ClientDetails to pass to the Serializer.
Can anyone point me out what I'm doing wrong here? Still learning.
Public Class JSON
Public Shared Function SerializeObject()
Dim clientdetails As New ClientDetails() With {.TransactionCount = "1", .TransactionType = "Q", .Transactions.TextA} 'Unable to Refer to any Property of Transactions.
'Dim Trans As New Transactions()
'Trans.TextA= "Test"
Dim output As String = JsonConvert.SerializeObject(clientdetails, Newtonsoft.Json.Formatting.Indented)
Return output
End Function
End Class
Public Class ClientDetails
Public Property Transactions As New Transactions()
Public Property [TransactionType] As String
Public Property [TransactionCount] As Integer
End Class
Public Class Transactions
Public Property [RecordID] As String
Public Property No As String
Public Property TextA As String
Public Property TextB As String
Public Property Initial As String
Public Property Flag As String
Public Property Sex As String
Public Property Area As String
Public Property Type As String
Public Property IDNO As String
End Class
You can use this syntax:
Dim clientdetails As New ClientDetails() With {.TransactionCount = "1", .TransactionType = "Q", .Transactions = New Transactions() With {.TextA = "Test"}}
Or a more readable code:
Dim trans As New Transactions
trans.TextA = "Test"
Dim clientDetails As New ClientDetails()
With clientDetails
.TransactionCount = "1"
.TransactionType = "Q"
.Transactions = trans
End With

Code to for AutoMapper complex mapping

AutoMapper with VB.NET
I have the following classes below. OrderA With List (Of OrderALineItem) and OrderBList With List (Of OrderB). I want to copy data from OrderA to OrderBList. Which copies ItemName, ItemQty, Price from List (Of OrderALineItem) to List (Of OrderB) and OrderID, CustomerName from OrderA itself. I have found almost all codes in C# and am not able to convert it to vb.net code.
Public Class OrderA
Public Property OrderID As String
Public Property CustomerName As String
Public Property OrderLineItem As List(Of OrderALineItem)
End Class
Public Class OrderALineItem
Public Property ItemName As String
Public Property ItemQty As Integer
Public Property Price As Decimal
End Class
Public Class OrderBList
Public Property OrderBLineItem As List(Of OrderB)
End Class
Public Class OrderB
Public Property OrderID As String
Public Property CustomerName As String
Public Property ItemName As String
Public Property ItemQty As Integer
Public Property Price As Decimal
End Class
My VB.NET code until now is:
Dim mapperConfiguration = New MapperConfiguration(Sub(config)
config.CreateMap(Of OrderALineItem, OrderBList)()
End Sub)
Dim mapper = mapperConfiguration.CreateMapper()
Dim objOrderB = mapper.Map(Of OrderBList)(objOrder.OrderLineItem)
The above code creates and object from copies the data from objOrder.OrderLineItem to OrderBList. That's it.
Can anybody help me out on this in VB.NET.
Note: Am totally new in AutoMapper
Version: AutoMapper 6.2.2.0
Done myself, I hope the code below will be helpful to somebody.
Dim mapperConfiguration = New MapperConfiguration(Sub(config)
config.AddProfile(New CustomProfile_1)
End Sub)
Dim objMapper = mapperConfiguration.CreateMapper()
Dim objOrderB As List(Of Dest_OrderB) = objMapper.Map(Of Src_OrderA, List(Of Dest_OrderB))(objOrderA)
Public Class CustomProfile_1
Inherits Profile
Sub New()
CreateMap(Of Src_OrderALineItem, Dest_OrderB)()
CreateMap(Of Src_OrderA, List(Of Dest_OrderB))() _
.ConstructProjectionUsing(
Function(Src1) Src1.List_Src_OrderALineItem.Select(Function(Src2) New Dest_OrderB _
With {.CustomerName = Src1.CustomerName,
.OrderID = Src1.OrderID,
.ItemName = Src2.ItemName,
.ItemQty = Src2.ItemQty,
.Price = Src2.Price}
).ToList())
End Sub
End Class

A referential integrity constraint violation occurred mvc4

i have this classes :
Public Class Customer
Public Property CustomerID As Integer
Public Property CustomerName As String
Public Property OrdersList As ICollection(Of Order)
End Class
Public Class Order
Public Property OrderID As Integer
Public Property CustomerID As Integer
Public Property OrderTotal As Decimal
Public Property OrderDetails As ICollection(Of OrderDetail)
Public Property OrderCustomer As Customer
End Class
Public Class OrderDetail
Public Property OrderDetailID As Integer
Public Property OrderID As Integer
Public Property ProductID As Integer
Public Property Price As Decimal
Public Property Quantity As Decimal
Public Property LineTotal As Decimal
Public Property OrderDetailOrder As Order
Public Property OrderDetailProduct As Product
End Class
Public Class Product
Public Property ProductID As Integer
Public Property ProductName As String
Public Property ProductPrice As Decimal
Public Property OrderDetails As ICollection(Of OrderDetail)
End Class
and this is the PUT Method
Function PutOrder(ByVal id As Integer, ByVal order As Order) As HttpResponseMessage
If ModelState.IsValid And id = order.OrderID Then
db.Entry(order).State = EntityState.Modified
Try
db.SaveChanges()
Catch ex As DbUpdateConcurrencyException
Return Request.CreateResponse(HttpStatusCode.NotFound)
End Try
Return Request.CreateResponse(HttpStatusCode.OK)
Else
Return Request.CreateResponse(HttpStatusCode.BadRequest)
End If
End Function
but when execute :db.Entry(order).State = EntityState.Modified
i have this error
A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.
thank u all
It means that
either order.CustomerID != order.OrderCustomer.CustomerID
or OrderDetail.OrderID != OrderDetail.OrderDetailOrder.OrderID for at least one of the OrderDetails
or OrderDetail.ProductID != OrderDetail.OrderDetailProduct.ProductID for at least one of the OrderDetails
You must ensure that those values are equal before you attach the order to the context.
i think this is the solution
Dim x = db.Orders.Include(Function(a) a.OrderDetails).Include(Function(o) o.OrderCustomer).FirstOrDefault
db.Entry(x).CurrentValues.SetValues(order)
thank u #Slauma ,your tips is helpfull