我的课程设计如下:
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);
}
}
但我认为必须有更好的解决方案。你能帮帮我吗?
答案 0 :(得分:1)
尝试更正您的类声明(virtual
和ICollection
)。同时确保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;}
}
答案 1 :(得分: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;
当@SlavaUtesinov回答时,第三个选项是virtual
和延迟加载。但是如果你事先知道你想要播放列表,就不需要延迟加载,它只会创建不必要的中间查询。
如果您想要加载视频列表并且只想访问某些视频的播放列表,而不是大多数/所有视频,则延迟加载将是一种很好的方式。