elboffor elboffor - 1 year ago 53
C# Question

c# filter database results using EF similar to SQL WHERE Clause

I've connected to my database using Entity Framework and am building my first MVC app for use in a web page.

I can get the controller to populate public strings in my models with no problem... the issue I'm having is that I can't figure out how to filter responses from my database.

I expect to have only one item returned which I will display in the view with


Here's my Model Class for the database table:

public partial class TBL_Wholesale_UWS_BusinessUnits
public int PrimaryID { get; set; }
public string BusinessUnit { get; set; }
public string Status { get; set; }

Here's what I have in my controller:

public ActionResult test(int PrimaryID)
var testing = new TBL_Wholesale_UWS_BusinessUnits();
// maybe putting new is the wrong thing to do as that would be wiping the class? IDK
return View(testing);

As you can see, the PrimaryID is passed to the controller via the querystring and this is recognised without issue, but I'm at a loss as to where to add the filter, I assumed it would be something like...

var testing = TBL_Wholesale_UWS_BusinessUnits.Where(TBL_Wholesale_UWS_BusinessUnits.PrimaryID = PrimaryID);`

but Visual Studio is telling me in no uncertain terms that this this wrong.

Had this been classic asp I would have just made a record set and used the where clause in SQL, but as this is built with the Entity Framework to do my connecting I don't really know where to start.

Any help would be greatly appreciated.

Answer Source

If you are only trying to return that one specific object to the view.. then you need to find that int PrimaryID in the database and retrieve that specific record.

What you are doing is simply creating a new instance of the TBL_Wholesale_UWS_BusinessUnits class which is empty.

Try this:

public ActionResult test(int PrimaryID)
    var testing = db.TableName.Find(PrimaryID);

    // db = Whatever the variable holding your connection string is.. maybe DbContext

    // TableName = Whatever table in your database that holds the record you want

    // This will return the specific object that you are looking for

    return View(testing);

I hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download