簡體   English   中英

將實體框架與 SQL Server 多對多關系一起使用

[英]Using Entity Framework with SQL Server many-to-many relations

不知道如何使用這里顯示東西的高級功能,所以請原諒;-)

數據庫結構為

User --> UserOwnerR <-- Owner

我也有幾個支持結構(例如屬於特定所有者的地址)。

我需要找到特定用戶有權訪問的所有地址,因為它屬於/許多所有者,但不是用戶與其有所有者關系的地址。

在 EF Core 5+ 中無需連接表即可實現 n:m 關系。

public class User
{
    // user properties 
    public IEnumerable<Owner> Owners { get; set; }

}

public class Owner
{
    // owner properties
    public IEnumerable<User> Users { get; set; }
}

您沒有指定您是使用 ef 代碼優先方法(您基於 c# 類生成架構)還是數據庫優先方法(從數據庫表生成 c# 類)或都不使用這些方法(手動設置實體)。

如果您能夠手動更改類,則可以添加導航屬性。 這些可能看起來像這樣:

public class User
{
    // whatever 
    public IEnumerable<UserOwnerR> userOwners { get; set; }

}

public class Owner
{
    // whatever
    public IEnumerable<UserOwnerR> userOwners { get; set; }

}

public class UserOwnerR
{
    public virtual Owner owner { get; set; }
    public virtual User user { get; set; }
}

現在,您可以在將這些表連接在一起時放置條件。 將基於 sql 語法的查詢選項與 linq 一起使用,因為這樣更容易連接您的表。 您可能想查看Entity Framework Join 3 Tables來構建您的個人查詢。

暫無
暫無

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

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