4
我有一個使用EF與數據庫接口的項目。它通過WCF Web服務完成此操作。這是我的第一個EF項目,我正在努力研究如何構建基於可選參數的查詢。基於可選搜索參數使用實體框架選擇數據
我的web服務有一個數據協定,其中包含與EF中的類匹配的字段。 Web服務提供數據庫服務,填充這些客戶端類並將其傳遞迴客戶端。舉一個例子....
在web服務
[DataContract]
public class MyMovie
{
[DataMember]
public int MovieId;
[DataMember]
public string MovieName;
[DataMember]
public int MovieRatingId;
[DataMember]
public string MovieRunTime;
[DataMember]
public string MovieIMDBUrl;
[DataMember]
public DateTime MovieDateAdded;
[DataMember]
public List<MyMovieActor> Actors;
[DataMember]
public List<MyMovieMedia> MediaFiles;
}
public class MyMovieActor
{
[DataMember]
public int ActorId;
[DataMember]
public int ActorMovieId;
[DataMember]
public string ActorName;
[DataMember]
public string ActorCharacter;
}
public class MyMovieMedia
{
[DataMember]
public int MediaId;
[DataMember]
public int MediaMovieId;
[DataMember]
public string MediaFileLocation;
[DataMember]
public bool MediaDefault;
}
數據模型(簡化的)...
我的web服務方法....
public MyMovie GetMovie(int movieId)
{
MyMovie response = new MyMovie();
using (MovieDatabaseEntities DbContext = new MovieDatabaseEntities())
{
var query = (from oData in DbContext.Movies
where oData.MovieId == movieId
select oData).ToList();
if (query.Count > 0)
{
response.MovieDateAdded = query[0].MovieDateAdded;
response.MovieId = query[0].MovieId;
response.MovieIMDBUrl = query[0].MovieIMDBUrl;
response.MovieName = query[0].MovieName;
response.MovieRatingId = query[0].MovieRatingId;
response.MovieRunTime = query[0].MovieRunTime;
}
List<MyMovieActor> actors = new List<MyMovieActor>();
foreach (MovieActor ma in query[0].MovieActors)
{
MyMovieActor a = new MyMovieActor();
a.ActorId = ma.ActorId;
a.ActorMovieId = ma.ActorMovieId;
a.ActorCharacter = ma.ActorCharacter;
a.ActorName = ma.ActorName;
actors.Add(a);
}
response.Actors = actors;
List<MyMovieMedia> medias = new List<MyMovieMedia>();
foreach (MovieMedia mm in query[0].MovieMedias)
{
MyMovieMedia med = new MyMovieMedia();
med.MediaId = mm.MediaId;
med.MediaMovieId = mm.MediaMovieId;
med.MediaFileLocation = mm.MediaFileLocation; //HDD Folder
med.MediaDefault = mm.MediaDefault; //Image to show on listing
medias.Add(med);
}
response.MediaFiles = medias;
}
return response;
}
所以現在我想創建
public List<MyMovie> GetMovies(string moviename, int movierating, string movieruntime)
其中將填充所有參數或零長度字符串。如果他們有一個值,我想添加它作爲where子句的一部分。
所以基本上更新
var query = (from oData in DbContext.Movies
where oData.MovieId == movieId
select oData).ToList();
到
var query = (from oData in DbContext.Movies
where 1=1
if(String.IsSafe(moviename))
{
&& oData.MovieName Like %movieId%
}
if(movierating != 0)
{
&& oData.MovieRating = movierating
}
if(String.IsSafe(movieruntime))
{
&& oData.MovieRuntime == movieruntime
}
select oData).ToList();
相當於展望這個剛剛困惑我更多,我一直用好老ADO.NET,的DataReader writen我的數據層,適配器,存儲過程等,但在這個項目中,我被要求使用EF。這讓我很困惑。他們怎麼說老狗和新花樣?
任何與此有關的幫助將非常感激。
完美!這三條線爲我節省了很多時間。非常感謝 – Fred