0

我有一个基于两个外键的表。一是memberID,二是movieID。我需要从该表中取出连接这两者的行并从同一行获取RentDays,即int.

我这样做了,但我认为它不好:

public int  GetRentDays(int memberID, string movieID)
{      
    var movieRentDays = 
        from Rents in videoLibDB.Rents
        where Rents.MemberID == memberID && Rents.MovieID == movieID
        select Rents.RentDays;
        return  movieRentDays ;
}
4

3 回答 3

0

Your code will work, but you can consider JOIN construction

var movieRentDays= from Rents in videoLibDB.Rents
                       join member in memberTable
                           on Rents.MemberID equals memberTable.memberID
                       join movie in movieTable
                           on Rents.MemberID equals movieTable.movieID
                   select Rents.RentDays;

var singleRentDay = movieRentDays.FirstOrDefault();
于 2012-11-06T19:33:33.077 回答
0

You are selecting an IEnumerable<int>, and returning the same variable, even though your method signature says you are returning an int. If you want to return just one int, and you are expecting just one from the LINQ statement, you can do something like this:

return
    (from Rents in videoLibDB.Rents
    where Rents.MemberID == memberID && Rents.MovieID == movieID
    select Rents.RentDays).FirstOrDefault();

See FirstOrDefault, SingleOrDefault, and Single.

于 2012-11-06T19:34:18.297 回答
0

尝试这个:

public int GetRentDays(int memberID, string movieID)
{      
    var movieRentDays = videoLibDB.Rents.FirstOrDefault
        (r => r.MemberID == memberID && r.MovieID == movieID);
    return movieRentDays == null || movieRentDays.HasValue ? 0 
        : movieRentDays.RentDays.Value;
}
于 2012-11-06T19:48:41.357 回答