0

I have a webpage and site using Linq. The page contains a gridview which shows customers and bound by a List (Of Customer).

I use the below code to get a single customer

    Public Function GetCustById(ByVal id As Integer) As Customer Implements ICustomerService.GetCustById
        Return DataContext.Customers.SingleOrDefault(Function(c) c.Id = id)
    End Function

I then bind it to my gridview by passing all the customer IDs into the method. This displays all the rows as i need but i have one issue.

Some columns which are Foreign keys show up as 1,2 etc, Usually the way i have overcome this in the past ON DIFFERENT PROJECTS is by adding a sub query to my SQL query in the data layer but as you've guessed this is Linq so im not sure what is /not possible in order to get the Foreign Keys to display as values using Linq?

Im a little new to Linq so appreciate any help or articles that would help me with this.

Thanks

7
  • Your question is not clear. Commented Apr 25, 2013 at 12:25
  • Linq is capable of Joins, use them to connect two tables. Commented Apr 25, 2013 at 12:29
  • Erm.... get the Foreign Keys to display as values using Linq? So im wondering if there is a way to get the above code to include the value of a Foreign Key (as you could do when writing a sub query in a tableadapter) Commented Apr 25, 2013 at 12:31
  • Could you show us an SQL Example? Commented Apr 25, 2013 at 12:33
  • SELECT Name, Address, Age, GenderID From Customer WHERE CustomerID=@CustomerID // This gets all the customer info with Gender being a FK. Here comes the sub query (SELECT GenderValue From Genders Where Customer.GenderID = Genders.ID) As GenderValue Commented Apr 25, 2013 at 12:37

1 Answer 1

1

It is recommended to separate the view from the entity classes (or domain classes if you like). So you will define a view model class, say CustomerViewModel, and project your Customer into it.

I'm not sure how you get a list of Customers (getting each single customer by Id is highly inefficient) but somewhere there will be an IEnumerable<Customer>. Let's call it customers. Now you can do

From c in customers_
Select New CustomerViewModel With { Name = c.Name, ... }

But now you can add properties to CustomerViewModel that are not in Customer! For instance

Select New CustomerViewModel
       With { Name = c.Name, TypeName = c.CustomerType.Name }

This CustomerType could be one of those foreign keys you want to show.

The result of the projection is an IEnumerable<CustomerViewModel> that you can show in the grid.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.