0

I am using linq in Asp.NET MVC project for database operations. I want to attract customers who have sitecode in the AgentHealth table. How can I do this with linq in one operation?

var CurrentCustomers = new List<Customer>();
var CurrentCustomersDisc = Database.Session
                                   .Query<agenthealts>()
                                   .ToList()
                                   .Select(x => x.sitecode)
                                   .Distinct()
                                   .ToList();

foreach(var CurrentDisc in CurrentCustomersDisc)
{
    var TempCustomer = Database.Session
                               .Query<Customer>()
                               .FirstOrDefault(x => x.deleted_at == null 
                                                 && x.SiteCode == CurrentDisc);
    if(TempCustomer != null)
    {
        CurrentCustomers.Add(TempCustomer);
    }               
}
5
  • Do you want to fetch one random customer from each agenthealth, SiteCode == CurrentDisc and place all these customers in a list? Commented Aug 27, 2017 at 9:51
  • Yes, CurrentCustomersDisc is an array of sitecodes and each customer has a sitecode. Commented Aug 27, 2017 at 9:53
  • Please check my answer. Furthermore, please update your question stating explicitly that you are looking for is a list that would contains a customer from each agenthealth, in order to be clear what is the questionable. Thanks Commented Aug 27, 2017 at 10:03
  • This looks like it could be done in a single simple query in SQL. I don't know about that linq-frontend-to-sql though. Is this Entity Framework? Commented Aug 27, 2017 at 10:07
  • 1
    @İsmail Kasap - Please tag the framework used - seems like NHibernate by the Session.Query, is that correct? Commented Aug 27, 2017 at 10:08

1 Answer 1

1

You can select customers where their Id (or what the primary key is) in `CurrentCustomersDisc':

var CurrentCustomers = Database.Session.Query<Customer>.Where(c=>
     CurrentCustomersDisc.Select(cc=> cc.Id).Contains(c.Id));
Sign up to request clarification or add additional context in comments.

1 Comment

Rica ederim ;) İsmail bey

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.