2017-10-20 303 views
0

我的類被設計這樣的:獲取財產的財產

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); 
    } 
} 

但我認爲必須有一個更好的解決方案。你能幫助我嗎?

回答

1

嘗試更正您的班級申報(virtualICollection)。另外,還要確保context.Configuration.LazyLoadingEnabled = true;

public class Video 
{ 
    public int Id {get; set;} 
    public string Title {get; set;} 

    public int PlaylistId {get; set;} 
    [ForeignKey("PlaylistId")] 
    public virtual Playlist Playlist {get; set;} 
} 

public class Playlist 
{ 
    public int Id {get; set;} 
    public string Description {get; set;} 

    public virtual ICollection<Video> Videos {get; set;} 
} 
0

如果您想選擇特定的東西,你可以選擇它們:

var playlist = context.Videos 
        .Where(x => x.Id == videoId) 
        .Select(x => x.Playlist) 
        .FirstOrDefault(); 

您還可以使用Include指定參考實體被加載

var video = context.Videos 
        .Include(x => x.Playlist) 
        .FirstOrDefault(x => x.Id == videoId); 
var playlist = video.Playlist; 

第三個選項將是virtual和@SlavaUtesinov回答的延遲加載。但是,如果您事先知道您需要播放列表,則不需要延遲加載,它只會創建不必要的中間查詢。

如果您想加載視頻列表,而您只想訪問某些視頻的播放列表,而不是大部分/全部視頻,則延遲加載將是一種好方法。