Linq к Объектам - SQL “В” пункте

В своем блоке each вы использовали @objective. Это nil

Использование objective.

<% @objectives.each do |objective| %>
  Objective:
  <%= objective.title %>
  Key Result:
  <% objective.keyresults.each do |keyresult| %>
    <%= keyresult.title %>
  <% end %>
<% end %>
228
задан shA.t 29 December 2015 в 20:28
поделиться

3 ответа

You need to turn it on its head in terms of the way you're thinking about it. Instead of doing "in" to find the current item's user rights in a predefined set of applicable user rights, you're asking a predefined set of user rights if it contains the current item's applicable value. This is exactly the same way you would find an item in a regular list in .NET.

There are two ways of doing this using LINQ, one uses query syntax and the other uses method syntax. Essentially, they are the same and could be used interchangeably depending on your preference:

Query Syntax:

var selected = from u in users
               where new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights)
               select u

foreach(user u in selected)
{
    //Do your stuff on each selected user;
}

Method Syntax:

var selected = users.Where(u => new[] { "Admin", "User", "Limited" }.Contains(u.User_Rights));

foreach(user u in selected)
{
    //Do stuff on each selected user;
}

My personal preference in this instance might be method syntax because instead of assigning the variable, I could do the foreach over an anonymous call like this:

foreach(User u in users.Where(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
    //Do stuff on each selected user;
}

Syntactically this looks more complex, and you have to understand the concept of lambda expressions or delegates to really figure out what's going on, but as you can see, this condenses the code a fair amount.

It all comes down to your coding style and preference - all three of my examples do the same thing slightly differently.

An alternative way doesn't even use LINQ, you can use the same method syntax replacing "where" with "FindAll" and get the same result, which will also work in .NET 2.0:

foreach(User u in users.FindAll(u => new [] { "Admin", "User", "Limited" }.Contains(u.User_Rights)))
{
    //Do stuff on each selected user;
}
345
ответ дан 23 November 2019 в 03:47
поделиться

Если вы используете VS2008 / .net 3.5, см. Совет Алекса Джеймса № 8: http://blogs.msdn.com/alexj/archive/2009/03/26/tip-8-writing-where-in-style-queries-using-linq-to-entities.aspx

В противном случае просто используйте метод array.Contains (someEntity.Member).

9
ответ дан 23 November 2019 в 03:47
поделиться

Я также пробовал работать с SQL-IN-подобной вещью - запрашивая модель данных сущности . Мой подход - построитель строк для составления большого ИЛИ-выражения. Это ужасно некрасиво, но, боюсь, сейчас это единственный путь.

Что ж, это выглядит так:

Queue<Guid> productIds = new Queue<Guid>(Products.Select(p => p.Key));
if(productIds.Count > 0)
{
    StringBuilder sb = new StringBuilder();
    sb.AppendFormat("{0}.ProductId = Guid\'{1}\'", entities.Products.Name, productIds.Dequeue());
    while(productIds.Count > 0)
    {
        sb.AppendFormat(" OR {0}.ProductId = Guid\'{1}\'",
          entities.Products.Name, productIds.Dequeue());
    }
}

Работа с GUID в этом контексте : Как вы можете видеть выше, есть всегда слово «GUID» перед самим GUID в фрагментах строки запроса. Если вы не добавите это, ObjectQuery .Where вызовет следующее исключение:

Типы аргументов 'Edm.Guid' и "Edm.String" несовместимы для этого операция., выражение почти равно, строка 6, столбец 14.

Обнаружил это на форумах MSDN, может быть полезно иметь в виду.

Маттиас

... с нетерпением жду следующей версии .NET и Entity Framework, когда все наладится . :)

2
ответ дан 23 November 2019 в 03:47
поделиться
Другие вопросы по тегам:

Похожие вопросы: