-2
\$\begingroup\$

I have a linq query that combines three tables:

  • Users,
  • Products, and
  • User_Has_Products

I am retrieving the

  • user.name,
  • product.name,
  • user_has_product.quantity, and
  • user_has_product.time

_

ViewBag.User_Has_Products = (from user_products in _context.Users_Has_Products
        join user in _context.Users on user_products.users_id equals user.id 
        join product in _context.Products on user_products.products_id equals product.id 
        select new{name =  user.name, product = product.name, 
quantity = user_products.quanitity, date = user_products.created_at});
\$\endgroup\$
3
  • 3
    \$\begingroup\$ It would be nice if you could provide the full schema for each table. I previously voted that this question is unclear but I retracted this vote. Without additional information it's hard to review it and comment on anything else then naming. \$\endgroup\$
    – t3chb0t
    Commented Jan 14, 2017 at 18:35
  • 1
    \$\begingroup\$ Additionaly you could mention what are your main concerns about this query if any. Performance? Don't you like the database schema? The join? \$\endgroup\$
    – t3chb0t
    Commented Jan 14, 2017 at 18:37
  • 1
    \$\begingroup\$ What is the purpose of this snippet? Without knowing the context of this code, there isn't much we can comment on. \$\endgroup\$
    – user34073
    Commented Jan 14, 2017 at 19:11

1 Answer 1

1
\$\begingroup\$

If the query does what you need and there aren't any performance problems then the only thing that can be improved is the formatting and naming.

You know that you can split the select into multiple lines? You also don't need the () becasue there is no extension attached to it like .ToList etc. One name is inconsitent with the others: user_products should be user_Has_Product.

Will you know that name is the user's name and not the product's name? The properties of the anonymous object should be PascalCase like all other property names.

ViewBag.User_Has_Products = 
    from user_products in _context.Users_Has_Products
    join user in _context.Users on user_products.users_id equals user.id 
    join product in _context.Products on user_products.products_id equals product.id 
    select new
    {
       Name = user.name, 
       Product = product.name, 
       Quantity = user_products.quanitity, 
       Date = user_products.created_at
    };

This table doesn't look right Users_Has_Products. Is this a look-up table? If so, I find the name UserProduct prettier, without the underscore in the name and the has that suggests it's something boolean. However when I see the properties user_Has_Product.quanitity and user_Has_Product.created_at I'm no longer sure about the look-up table theory.

\$\endgroup\$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.