Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4172670
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T00:35:28+00:00 2026-05-21T00:35:28+00:00

I don’t know Linq2Sql so well yet and I was wondering if there is

  • 0

I don’t know Linq2Sql so well yet and I was wondering if there is a trick for this probably common MVVM scenario. I have Linq2Sql data context containing Domain models, but I am fetching data for my customized ViewModel object from it.

var query = from ord in ctx.Table_Orders
        select new OrderViewModel()
        {
            OrderId = ord.OrderId,
            OrderSum = ord.OrderSum,
            OrderCurrencyId = ord.OrderCurrencyId,
            OrderCurrencyView = ord.Currency.CurrencyText
        };

So i want my ViewModel to inculde both CurrencyId from domain object and the CurrencyText from related table to show it nicely in the View.

This code works great. It generates one DB call with join to fetch the CurrencyText. But the model is simplified, real one has many more fields. I want to make the code reusable because I have many different queries, that returns the same ViewModel. Now every minor change to OrderViewModel requires lots of maintainance.

So I moved the code to OrderViewModel itself as a constructor.

public OrderViewModel(Table_Order ord)
{
    OrderId = ord.OrderId,
    OrderSum = ord.OrderSum,
    OrderCurrencyId = ord.OrderCurrencyId,
    OrderCurrencyView = ord.Currency.CurrencyText
}

And call it like this.

var query = from ord in ctx.Table_Orders
        select new OrderViewModel(ord);

The Problem: The join is gone DB query is no more optimised. Now I get 1+N calls to database to fetch CurrencyText for every line.

Any comments are welcome. Maybe I have missed different great approach.

This is how far i could get on my own, to get the code reusability. I created a function that does the job and has multiple parameters. Then I need to explicitly pass it everything that has crossed the line of entity.

var query = ctx.Table_Orders.Select(m =>
       newOrderViewModel(m, m.Currency.CurrencyText));

The DB call is again optimized. But it still does not feel like I am there yet! What tricks do You know for this case?


EDIT : The final solution
Thanks to a hint by @Muhammad Adeel Zahid I arrived at this solution.
I created an extension for IQueryable

public static class Mappers
{
    public static IEnumerable<OrderViewModel> OrderViewModels(this IQueryable<Table_Order> q)
    {
        return from ord in q
                select new OrderViewModel()
                {
                    OrderId = ord.OrderId,
                    OrderSum = ord.OrderSum,
                    OrderCurrencyId = ord.OrderCurrencyId,
                    OrderCurrencyView = ord.Currency.CurrencyText
                };
    }
}

Now i can do this to get all list

var orders = ctx.Table_Order.OrderViewModels().ToList();

or this to get a single item, or anything in between with Where(x => ..)

var order = ctx.Table_Order
   .Where(x => x.OrderId == id).OrderViewModels().SingleOrDefault();

And that completely solves this question. The SQL generated is perfect and the code to translate objects is reusable. Approach like this should work with both LINQ to SQL and LINQ to Entities. (Not tested with the latter) Thank You again @Muhammad Adeel Zahid

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-21T00:35:29+00:00Added an answer on May 21, 2026 at 12:35 am

    Whenever we query the database, we mostly require either enumeration of objects (more than one records in db) or we want a single entity (one record in db). you can write your mapping code in method that returns enumeration for whole table like

    public IEnumerable<OrderViewModel> GetAllOrders()
    {
        return from ord in ctx.Table_Orders
            select new OrderViewModel()
            {
                OrderId = ord.OrderId,
                OrderSum = ord.OrderSum,
                OrderCurrencyId = ord.OrderCurrencyId,
                OrderCurrencyView = ord.Currency.CurrencyText
            };
    
    } 
    

    Now you may want to filter these records and return another enumeration for example on currencyID

    public IEnumerable<OrderViewModel> GetOrdersByCurrency(int CurrencyID)
    {
          return GetAllOrders().Where(x=>x.CurrencyId == CurrencyID);
    }
    

    Now you may also want to find single record out of all these view models

    public OrderViewModel GetOrder(int OrderID)
    {
          return GetAllOrders().SingleOrDefault(x=>x.OrderId == OrderID);
    }
    

    The beauty of IEnumerable is that it keeps adding conditions to query and does not execute it until it is needed. so your whole table will not be loaded unless you really want it and you have kept your code in single place. Now if there are any changes in ViewModel Mapping or in query itself, it has to be done in GetAllOrders() method, rest of code will stay unchanged

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Don't overthink this - there's a very commonly used term and I ... have
Don't know if this has been answered before. Have custom routes to users. If
Don't know why but I can't find a solution to this. I have 3
Don't know if there is a better way to do this, so that is
Don't know how to google for such, but is there a way to query
(Don't know if this is strictly on-topic, but I don't see any better Stack
Don't know if this has been asked before, so point me to another question
Don't know if anyone can help me with this or if it's even possible.
I don't know: if this works. if it's a good idea. what it is
I don't know if this question is trivial or not. But after a couple

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.