简体   繁体   English

在MVC4和C#中的不同控制器中重构LINQ查询

[英]Refactor LINQ queries in different controllers in MVC4 and C#

I am trying to apply the DRY (Do Not Repeat Yourself) to my MVC4 program. 我试图将DRY(请勿重复)应用于我的MVC4程序。

I have two LINQ queries in two different controllers. 我在两个不同的控制器中有两个LINQ查询。

The queries are the same. 查询是相同的。

What is the best way to make the query available to both controllers. 使查询可用于两个控制器的最佳方法是什么。

Thank you in advance for suggestions. 预先感谢您的建议。

Based on what you've said, the LINQ statements are the same, correct? 根据您所说的,LINQ语句是相同的,对吗? For example, getting a list of active hourly employees, in stock inventory items or such. 例如,获取库存清单项目等中的小时工活跃列表。

In this situation, it would probably be best to add these commonly used methods to your Entity model. 在这种情况下,最好将这些常用方法添加到您的实体模型中。 If you generated the classes, they're partial classes so you would simply create a partial class with the routines you need to retrieve the commonly used data. 如果生成了这些类,则它们是部分类,因此您只需使用需要检索常规数据的例程来创建部分类。 This class would go in your models folder. 此类将放在您的models文件夹中。 It would look something like this... 看起来像这样...

namespace MyNamespace.Models
{
    public partial class MyEntities
    {

        IQueryable<InventoryItem> InStockInventoryItems()
        {
            return this.InventoryItems.Where(m => m.Quantity > 0);
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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