简体   繁体   中英

Using an MVC Model as a filter in the repository

I have a details view that is typed to IEnumerable. The view with a bunch of drop downs that let you add filters to the list of records rendered.

All these dropdowns correspond to properties on the MVC model:

public class Record
{
    public string CustomerNumber { get; set; }
    public string CustomerName { get; set; }
    public string LineOfBusiness{ get; set; }
    public DateTime? Date { get; set; }
}

Now, I'm using my model as my dto to shuffle data between my controller and my repo. Since all my drop down filters represent the model properties, I pass my model to a repo retrieval method, check its properties and filter based on its values? In other words:

 public IEnumerable<TradeSpendRecord> Get(TradeSpendRecord record)
    {
        IQueryable<tblTradeSpend> query = _context.tblRecords;


        if (!String.IsNullOrEmpty(record.CustomerName))
            query = query.Where(x => x.CustomerNumber == record.CustomerNumber);

        if (!String.IsNullOrEmpty(record.LineOfBusiness))
            query = query.Where(r => r.LOB == record.LineOfBusiness);

SNIP

Hope this isn't too subjective, but I'm wondering if anyone has any input about whether this is a good/bad practice. I haven't seen a whole lot of examples of dynamic filtering like I need to do, and am looking for some guidance.

Thanks,

Chris

If you're doing what I think you're doing, I'm not sure this is the best way of doing it.

Keep your 'Models' in your MVC/presentation layer (whether this is one physical assembly or not) dedicated to your presentation layer. The only things that should be touching them are your Views and your Controllers. You don't want what should be independent entities to be so tightly coupled to your View Models.

I'd suggest creating a separate TradeSpendFilter class, which, at its simplest, exposes the filterable properties of your domain entity (likely more than any given View Model). You'd then pass this into your "filtering service" or whatever it may be. This also means you can extend your filtering functionality independent of both your domain models and your MVC app. For example, if you suddenly want to filter multiple objects, you can simply change...

public class TradeSpendFilter
{
    public string CustomerName { get; set; }
    ...
}

...to...

public class TradeSpendFilter
{
    public IEnumerable<string> CustomerNames { get; set; }
    ...
}

... without causing all sorts of problems for your MVC app.

Additionally, it will also mean you can make use of your filtering functionality elsewhere, without tying further components to your MVC app and ending up in a bootstrapped mess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM