Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .where extension method causes duplicates (MVC-LINQ)

I am trying to create a partial view to display some data. My controller takes in a string itemID and performs a query based on that. When the partial view is called, it displays the same record over and over again.

Note: I changed the name of objects for security purposes.

[ChildActionOnly]
public ActionResult someAction(string itemID = "")
{
    //Empty itemID
    if(string.IsNullOrEmpty(itemID))
    {
        return RedirectToAction("Index", "Search");
    }

    var model = _db.someTable
            .Where(r => r.itemID == itemID)
            .OrderBy(r => r.col1)
            .ThenBy(r => r.col2)
            .Take(20);
    return PartialView("_myView", model);
}

I have tried removing the OrderBy and ThenBy methods, but the result remain the same, (Order would not matter since they are duplicates...). When I remove the .Where method, it works as expected and displays 20 different records (though, not filtered by any means).

My view was created by Visual Studio using the List template. The view been proven working by removing the .Where method from the LINQ statement. Here are the important bits of the view:

@model IEnumerable<MyApp.Models.OperationData>
.
.
.
@foreach (var item in Model) {
<tr>
    <td>
        @Html.DisplayFor(modelItem => item.some column)
    </td>
.
.
.

Any ideas as to what is wrong with this query?

EDIT: Tried the other LINQ syntax and ended up with the same results:

var model = from r in _db.someTable where r.itemID == itemID select r;
like image 213
Jeff Avatar asked Mar 11 '26 04:03

Jeff


1 Answers

Winner winner chicken dinner!

Turns out the issue was with the mapping of model to table. The table I was working on has a composite key, which I didn't know about... After reading mipe34's bit about primary keys, I decided to do some investigation into the table structure. After discovering the composite keys, I added the mapping for the 2nd key and all works well.

This issue was extremely confusing since the SQL generated by LINQ worked perfectly fine when run in SQL Management Studio.

Thanks all!

like image 74
Jeff Avatar answered Mar 12 '26 21:03

Jeff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!