簡體   English   中英

來自非關系數據庫的 EF Core 5.0 關系

[英]EF Core 5.0 relational from non-relational db

所以這就是問題所在。

我有一個來自舊 COBOL 軟件(txt 文件)的古老數據庫。

我想要的是

  • 關聯下面列出的對象而不更改原始數據。

背景

數據庫是 MS-SQL。 每個導入的 object 都有一個唯一的 id(數據庫生成)。 舊 COBOL 軟件中實際組合對象的“外鍵”(“NonUniqueItemProperty”)不是唯一的。 (這就是為什么我不能在表之間創建關系)

我的問題是,這甚至可能嗎?

目前我加入查詢表為

select item.*,owner.* from Items item
INNER JOIN Ownership ownership on item.NonUniqueItemProperty=ownership.NonUniqueItemProperty
INNER JOIN Owner owner on ownership.OwnerIdNo=owner.OwnerIdNo

此查詢返回匹配結果集 (item-->ownerCount)*(item-->count)。 然后我使用 linq 按 Item.NonUniqueItemProperty 對它們進行分組,並為每個項目設置所有者。

對象:

    public class Item
    {
        pullic int Id {get;set;} // database generated, non-related to original data
        public string NonUniqueItemProperty {get;set;} //sadly this is the identifier
        public virtual ICollection<Ownership> Ownerships { get; set; }
    }
    
    public class Ownership
    {
        pullic int Id {get;set;} // database generated, non-related to original data
        public virtual Item Item { get; set; }
        public virtual Owner Owner { get; set; }
        public string NonUniqueItemProperty {get;set;}
        public string OwnerIdNo {get;set;}
    }
    
    public class Owner
    {
        pullic int Id {get;set;} // database generated, non-related to original data
        public virtual ICollection<Ownership> Ownerships { get; set; }
        public string OwnerIdNo {get;set;}
    }

我試圖在流利的 api 建立關系:

    item.HasMany<Ownership>(i => i.Ownerships)
                .WithOne(ow => ow.Item)
                .HasPrincipalKey(i=>i.NonUniqueItemProperty)
                .HasForeignKey(ow=>ow.NonUniqueItemProperty);

就目前而言,沒有錯誤,但導航屬性為 null。

編輯

在此之后,我意識到這個表達式返回一個帶有 null 所有權導航的 Item 實體。 結果集返回了我要查找的內容,因此導航可用於過濾項目集!

var resultSet = ctx.Items.Where(
             i => i.Ownerships.Any(
                     ow => ow.Owner.OwnerIdNo=="P12345"));

我設法通過 Eager Loading 獲得導航屬性,並在此處解釋

通過將Include(i=>i.Ownership).ThenInclude(ow=>ow.Owner)添加到查詢的末尾。

但是根據兩位領域專家的建議,這不應該起作用,我不打算在代碼中實現它,這在 EF 的更高版本中也不起作用。

編輯

這是一個真正的性能殺手,通過編寫上面的 sql-query,TOP 150 項消耗 120-150 毫秒。 這個是 2.500-4.000 毫秒( query.Take(100) )。

(項目數:350K,所有權數:390K)

暫無
暫無

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

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