簡體   English   中英

使用linq加載導航屬性而無需聲明外鍵

[英]Use linq to load Navigation Property without Declaring Foreign Key

我所參與的項目首先使用Entity Framework 6,並具有代碼,並且具有中央數據庫和本地數據庫。 中央數據庫與本地數據庫相同,除了已刪除所有關系(外鍵,主鍵等)。

因此,假設我有以下課程:

public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public int ProductTypeId { get; set; }
    public ProductType ProductType { get; set; }
}

public class ProductType
{
    public int ProductTypeId { get; set; }
    public string Name { get; set; }
    public List<Product> Products { get; set; }
}

如果數據庫在Product表中有外鍵,我可以做

IEnumerable<Product> products = ctx.Produts.Include(x => x.ProductType);

如果datbase沒有外鍵,EF仍會使用上面的代碼加載ProductType對象嗎?

沒有外鍵,EF將不會加載ProductType對象。

您將需要執行一個新查詢。 像這樣:

IEnumerable<Product> products = ctx.Produts;

foreach (var product in products )
{
   ProductType type = (from t in ctx.ProductType where t.ProductTypeId == product.ProductTypeId select t).Single();    
   product.ProductType = type;
}

我對此感到很好奇,因此我模擬了一個快速測試,無論是否在數據庫中都使用外鍵,我都運行了該測試。 答案似乎是肯定的,只要您仍在Entity Framework中配置了密鑰,它就會起作用。 但是請注意,當然,盡管看起來像EF一樣,但沒有鍵,數據庫顯然不會強制執行引用約束。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM