我的类被设计这样的:获取财产的财产
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);
}
}
但我认为必须有一个更好的解决方案。你能帮助我吗?