0

Customer テーブルから customerId を取得しようとしています。

ただし、作成しようとすると、「型 'System.Linq.Iqueryable' を 'int' に暗黙的に変換できません」というエラーが表示されます。

どうすればcustomerIdを取得できますか??

ありがとうございました。

これが私のコーディングです。

int customerId = from a in db.Customer
                            where a.userName == customerName
                            select a.customerId; 
                           //it has error in here.

order.customerId = customerId;
4

4 に答える 4

3

クエリが複数の行を返す可能性があります。最初の (または単一の) 結果のみが必要であることを LINQ に伝える必要があります。

int customerId = (from a in db.Customer
                  where a.userName == customerName
                  select a.customerId).First();
于 2012-04-16T16:35:46.683 に答える
1

行が 1 つしかないことがわかっている場合は、.Single() 関数を使用するのが好きです。

int customerId = (from a in db.Customer
                  where a.userName == customerName
                  select a.customerId).Single(); 

これは、見つかった行が 1 行より多いか少ない場合に例外をスローします。これは、状況によっては役立つ場合があります。

于 2012-04-16T17:45:12.423 に答える
0

次のように使用します: var customer = db.Customer.FirstOrDefault(c =>c.userName == customerName) var id = customer.Id

Select は IEnumerable を返すため、int に変換することはできません。

于 2012-04-16T16:36:13.273 に答える
0

この質問に対してお勧めできるもう 1 つの提案は、First または default を使用することです。

var customerId = (from a in db.Customer
                            where a.userName == customerName
                            select a.customerId).FirstOrDefault(); 

order.customerId = customerId;int を既に認識しているため、これで問題なく動作するはずです。

于 2012-04-16T16:39:29.717 に答える