下面創建一個表,但允許您可能不希望加載的字段(在這種情況下,稱爲Data
的字節數組)的引用/導航屬性。這被稱爲表分割。
主要注意事項是讓兩個實體都使用TableAnnotion
映射到同一個表(duh),並共享相同的主鍵,該主鍵用作相互導航屬性的外鍵。
[Table("Document")]
public class Document
{
[Key]
[ForeignKey("Data")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int DocumentId { get; set; }
public string FileName { get; set; }
public DateTime Created { get; set; }
public virtual DocumentData Data { get; set; }
}
[Table("Document")]
public class DocumentData
{
[Key]
[ForeignKey("Document")]
public int DocumentId { get; set; }
public byte[] Data { get; set; }
public virtual Document Document { get; set; }
}
public class DocEntities : DbContext
{
public DocEntities()
: base("name=TestEntitiesCodeFirst")
{
}
public DbSet<Document> Documents { get; set; }
}
static void Main(string[] args)
{
using (var db = new InheritTest.DocEntities())
{
var doc = new Document()
{
Created = DateTime.Now,
FileName = "Abc.txt",
Data = new DocumentData()
{
Data = new byte[] { 0x50, 0x51, 0x52, 0x53 }
}
};
db.Documents.Add(doc);
db.SaveChanges();
}
using (var db = new InheritTest.DocEntities())
{
db.Configuration.LazyLoadingEnabled = false;
var doc = db.Documents.First();
if (doc.Data == null)
{
Console.WriteLine("doc.Data is null");
}
db.Entry(doc).Reference(p => p.Data).Load();
if (doc.Data != null)
{
Console.WriteLine("doc.Data is not null");
Console.WriteLine(doc.Data.Data.Length);
}
}
var input = Console.ReadLine();
}
結果表:
CREATE TABLE [dbo].[Document](
[DocumentId] [int] IDENTITY(1,1) NOT NULL,
[FileName] [nvarchar](max) NULL,
[Created] [datetime] NOT NULL,
[Data] [varbinary](max) NULL,
CONSTRAINT [PK_dbo.Document] PRIMARY KEY CLUSTERED
(
[DocumentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
的可能的複製http://stackoverflow.com/questions/5756890/lazy-load-for-nonnavigation-property-in-ef-4-1 –
你可以創建一個只有圖像數據的新表格,並使用相同的主鍵鏈接它們。然後你的財產成爲導航財產,它可以被延遲加載。 – Shoe
這就是關聯問題所說的。 –