我的類被設計這樣的:獲取財產的財產
public class Video {
public int Id {get; set;}
public string Title {get; set;}
public int PlaylistId {get; set;}
[ForeignKey("PlaylistId")]
public Playlist Playlist {get; set;}
}
public class Playlist {
public int Id {get; set;}
public string Description {get; set;}
public List<Video> Videos {get; set;}
public Playlist() {
Videos = new List<Video>();
}
}
而現在,讓我們創建一些對象:
Video video = new Video();
video.Title = "Titanic";
Playlist playlist = new Playlist();
playlist.Description = "Best videos";
playlist.Videos.Add(video);
context.Playlists.Add(playlist);
context.SaveChanges();
的問題是我無法從我的數據庫上下文video.Playlist
參考。當然,我可以添加一個獲得想要的財產的方法:
public static Playlist GetPlaylist(int videoId) {
using (var context = new DatabaseContext()) {
Video video = context.Videos.FirstOrDefault(x => x.Id == videoId);
return context.Playlists.FirstOrDefault(x => x.Id == video.PlaylistId);
}
}
但我認爲必須有一個更好的解決方案。你能幫助我嗎?