简体   繁体   English

将实体框架与 SQL Server 多对多关系一起使用

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

Do not know how to use the advanced features of displaying thing here, so please excuse ;-)不知道如何使用这里显示东西的高级功能,所以请原谅;-)

The database structure is数据库结构为

User --> UserOwnerR <-- Owner

Also I have several support structures (ex. addresses belonging to a specific owner).我也有几个支持结构(例如属于特定所有者的地址)。

I need to find all addresses to whom a specific user has access because it belongs to on/many owners, but not addresses to whom the user have a owner relation.我需要找到特定用户有权访问的所有地址,因为它属于/许多所有者,但不是用户与其有所有者关系的地址。

n:m relations can be realized without a join table in EF Core 5+.在 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; }
}

You did not specify wether you're using ef Code first approach (you generated your Schema based on c# classes) or database first approach (generate c# classes from database tables) or none of those (manually set up your entities).您没有指定您是使用 ef 代码优先方法(您基于 c# 类生成架构)还是数据库优先方法(从数据库表生成 c# 类)或都不使用这些方法(手动设置实体)。

If you are able to change your classes manually, you might add navigation properties.如果您能够手动更改类,则可以添加导航属性。 Those might look like this:这些可能看起来像这样:

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; }
}

Now you are able to place conditions while joining those tables together.现在,您可以在将这些表连接在一起时放置条件。 Use the sql syntax based query option with linq, as it's easier to connect your tables that way.将基于 sql 语法的查询选项与 linq 一起使用,因为这样更容易连接您的表。 You might want to take a look at Entity Framework Join 3 Tables to construct your individual query.您可能想查看Entity Framework Join 3 Tables来构建您的个人查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM