1
假設我有兩個波蘇斯:EF導航性能並節省
public class Album {
public int ID { get; set; }
[Required]
public string Title { get; set; }
public short Rating { get; set; }
public int ArtistID { get; set; }
[Required]
public virtual Artist Artist { get; set; }
}
public class Artist {
public int ID { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Album> Albums { get; set; }
}
,然後我執行一些像這樣的代碼:
using (PickContext db=new PickContext()) {
Album pick=db.Albums.SingleOrDefault(a => a.ID==pickID);
if (pick==null) return;
pick.Rating=4;
db.SaveChanges();
我很驚訝,我得到了這樣一個驗證異常:
Property: "Artist", Error: "The Artist field is required."
當我改變了我的查詢,包括藝術家:
Album pick=db.Albums.Include("Artist").SingleOrDefault(a => a.ID==pickID);
我不再有例外。如果我不告訴EF來填充所有屬性,並且它們不是必需的,它是否會簡單地覆蓋數據庫中的這些FK?我會認爲如果我檢索一個實體並且不分配一個屬性,該屬性將不會在數據庫中進行更改。這是不是真的?