简体   繁体   English

实体框架核心关系集合为空

[英]Entity framework core relationship collection is empty

I did do a database first approach, and I did make my database. 我确实做了数据库第一种方法,我确实创建了我的数据库。 I use relationship and I have two tables: 我使用关系,我有两个表:

users
-------------
id PK int(11)
username UNIQUE varchar(20)

rooms
-------------
id PK int(11)
name VARCHAR(30) NOT NULL
owner_id INDEX int(11) -> FK to users.id

When I do a scaffold, the models look a little like this: 当我做脚手架时,模型看起来有点像这样:

User.cs: User.cs:

public User()
{
    Rooms = new HashSet<Room>();
}

public int Id { get; set; }
public string Username { get; set; }
public virtual ICollection<Room> Rooms { get; set; }

Room.cs: Room.cs:

public int Id { get; set; }
public string Name { get; set; }
public int? OwnerId { get; set; }

public virtual User Owner { get; set; }

(the OwnerId is nullable since system rooms don't have an assigned owner) (OwnerId可以为空,因为系统房间没有指定的所有者)

The problem is, if I have my user object obtained when logging in, and I view user.Rooms , the collection is always empty, even though the database has an entry. 问题是,如果我在登录时获得了我的用户对象,并且我查看了user.Rooms ,则该集合始终为空,即使数据库有一个条目。

I know include fixes this, but that makes me have to load ALL rooms from the database, which is a terrible idea when there's like 1000+ rooms being loaded on start of the program. 我知道包括修复这个,但这使我必须从数据库加载所有房间,这是一个可怕的想法,当在程序的开始加载1000多个房间。

Why is the collection always empty even though the relationships are setup correctly? 即使关系设置正确,为什么集合总是为空?

Setting up relationsips are different from loading related entities on memory. 设置关系片与在内存上加载相关实体不同。 There are 4 different loading mechanisms you can choose according to your needs. 您可以根据需要选择4种不同的加载机制。

  1. Eager(Include and ThenInclude) 渴望(包括然后包括)
  2. Explicit 明确的
  3. Lazy Loading(EF Core 2.1) 延迟加载(EF Core 2.1)
  4. Select Loading 选择加载

You can use select loading to filter which related entites must be loaded. 您可以使用选择加载来过滤必须加载哪些相关的entites。 So you do not need to load all related entitites. 因此,您无需加载所有相关的权限。

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

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