2

1対多の外部キーを含むデータベースがあります。

Table {shop
[Id]
...}

Table {user
[Id]
[Shop_id]
[Archived]
}

以下のような方法もあります

public IEnumerable<shop> GetShopDetails(int shopId)
{
    var foo = (from s in context.Shops
    where s.Id = shopId
    select s).ToList();

    return foo;
}

この結果、そのショップのすべてのユーザーが返されます。ほとんどの場合、アーカイブされていないユーザーのみが本当に必要です。

これを 1 つのステートメントに書き込む方法はありますか。つまり、includeArchived の 2 番目のパラメーターを渡し、それを使用して、すべてのユーザーを返すか、アクティブなユーザーだけを返すかを決定できます。

現時点では、ユーザーのサブセットを返すメソッドをショップ オブジェクトに追加するか、ショップを読み込んでその ID を取得し、適切な fk を含むユーザーの別のコレクションを作成することで機能させることができますが、どちらの方法も私には少し不格好に思えます。

4

2 に答える 2

2

条件付きで別の条件を追加するだけWhereです:

public IQueryable<user> GetShopUsers(int shopId, bool includeArchived = false)
{
    var foo = from u in context.Users
              where u.Shop_id = shopId
              select u;

    if(!includeArchived)
        foo = foo.Where(u => !u.Archived);  

    return foo;
}
于 2013-03-19T14:22:46.593 に答える
0

私はこれがあなたが望むものだと思いますか?で行ったのと同じように、別のブール値パラメータをクエリに統合できますshopId

public IQueryable<user> GetUsers(int shopId, bool includeArchived)
{
    return from user in context.Users
           where user.Shop_id = shopId
           where includeArchived || !user.Archived
           select user;
}

更新: ショップ エンティティの独自のユーザー コレクションをフィルター処理できるかどうかはわかりません。匿名オブジェクトを構築するクエリを試すことができます。

var foo = from s in context.Shops
          where s.Id = shopId
          select new {
              Shop = s,
              Users = s.Users.Where(u => includeArchived || !u.Archived)
          };
于 2013-03-19T14:22:51.973 に答える