public class Photograph { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int PhotoId { get; set; } public string Title { get; set; } public byte[] ThumbnailBits { get; set; } [ForeignKey("PhotoId")] public virtual PhotographFullImage PhotographFullImage { get; set; } } public class PhotographFullImage { [Key] public int PhotoId { get; set; } public byte[] HighResolutionBits { get; set; } [ForeignKey("PhotoId")] public virtual Photograph Photograph { get; set; } } public class PhotoContext : DbContext { public DbSet<Photograph> Photographs { get; set; } public DbSet<PhotographFullImage> PhotographFullImages { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Photograph>() //配置必需關係。 數據庫中的外鍵不可爲 null不然沒法保存到數據庫。 .HasRequired(p => p.PhotographFullImage) //做爲關係目標的主體類型將成爲依賴對象,且包含主體的外鍵 .WithRequiredPrincipal(p => p.Photograph); modelBuilder.Entity<Photograph>().ToTable("Table1"); modelBuilder.Entity<PhotographFullImage>().ToTable("Table2"); } }
static void Main(string[] args) { var thumbBits = new byte[100]; var fullBits = new byte[2000]; using (var context = new PhotoContext()) { var photo = new Photograph { Title = "小狗", ThumbnailBits = thumbBits }; var fullImage = new PhotographFullImage { HighResolutionBits = fullBits }; photo.PhotographFullImage = fullImage; context.Photographs.Add(photo); context.SaveChanges(); } using (var context = new PhotoContext()) { foreach (var photo in context.Photographs) { Console.WriteLine("照片: {0}, 壓縮 {1} bytes", photo.Title, photo.ThumbnailBits.Length); // 顯式地加載了「昂貴」的實體 context.Entry(photo).Reference(p => p.PhotographFullImage).Load(); Console.WriteLine("原始: {0} bytes", photo.PhotographFullImage.HighResolutionBits.Length); } Console.ReadKey(); } }