Entity Framework - Linq To Entities - Many-To-Many Query Problems

那年仲夏 提交于 2019-12-03 03:31:48

Try this,

var result = from c in ctx.Customer
             from i in c.Interest
             where i.InterestName == "Football"
             select c;

Hope this helps,

Ray.

Daniel Brückner

I am not sure what you want to obtain. A list of customers with a customer interest and a interest? Just start the query at customer interest.

context.CustomerInterest.
   Where(ci => ci.Interest.InterestName == "Football").
   Select(ci => new
   {
      Customer = ci.Customer,
      CustomerInterest = ci,
      Interest = ci.Interest
   });

But this is highly redundant. Why not just get the matching customer interests?

IEnumerable<CustomerInterest> customerInterests = context.CustomerInterest.
   Where(ci => ci.Interest.InterestName == "Football");

You can still access the other information without needing to store it explicitly.

foreach (CustomerInterest customerInterest in customerInterests)
{
   DoSomething(customerInterest);
   DoSomething(customerInterest.Customer);
   DoSomething(customerInterest.Interest);
}
        var results = from c in _CRM.Customer
                      from ci in c.Interests
                      join i in _CRM.Interests
                      on ci.ID equals i.ID
                      where i.Interest = "Football"
                      select c;

If you trying to keep it generic, better way is to go with entity sql[Esql]. Coz L2E doesn't support where for collections in linq query.

You cannot use

customer.Interests.Where(interest => interest.Name =='FootBall')

The query would look like this..

context.CreateQuery(@"SELECT VALUE Customer FROM Customer WHERE EXISTS( SELECT VALUE FROM CustomerInterest WHERE CustomerInterest.Ineterest.Name = 'FootBall')).Include("Interest");

hope it helps!

That's to much for LINQT. Try use a view at your database or work as Deepak N said. Best

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!