简体   繁体   中英

How to improve LINQ repository query in MVC 4

I'm new to MVC and I'm trying to write a method (CheckIfDeletePossible) that checks whether the given CurrencyID is being used in the ProjectCurrency table.

Following is my first attempt and the query appears to be very slow.

Is there any better way to check this without looping the project table?

Currency Controller:

       private bool CheckIfDeletePossible(int currencyID)
       {
        var lIsUsed = false;

        var projectCurr = projectRepository.All;
        foreach (var projects in projectCurr){

            var project = projectRepository.AllIncluding(p => p.ProjectCurrencies.Select(c => c.Currency))
                            .Where(x => x.ProjectID == projects.ProjectID)
                            .Single();

            var projCurrency = from projCurr in project.ProjectCurrencies
                               where projCurr.Currency.CurrencyID == currencyID
                               select projCurr.Currency;

            if (projCurrency.Count() > 0)
            {
                lIsUsed = true;
                return lIsUsed;
            }
        }

        return lIsUsed;
    }

Project Model:

public partial class Project: 
{
    public Project()
    {
        ProjectCurrencies = new List<ProjectCurrency>();

    }

    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    [Display(Name="ID")]
    public int ProjectID { get; set; }

    [Required]
    [Display(Name = "Project Title")]
    public string Title { get; set; }


    [Display(Name = "Currency Rates")]
    public virtual List<ProjectCurrency> ProjectCurrencies { get; set; }


}

You have added unnecessary complexity to your method, and the foreach is not needed.

You can check if a currency is used in a project with a snippet of code as simple as:

using (var repo = new ProjectRepository())
{
    var used = repo.AllIncluding(p=>p.ProjectCurrencies)
        .Any(p => p.ProjectCurrencies.Any(pc => pc.Currency.CurrencyID == 2));
}

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