C
C#6mo ago
Denis

✅ EF Core include only one property of collection

var query = db.Projects
.Include(static project => project.Owner)
.Include(static project => project.OwnerGroup)
.Where(p => p.ParentProjectId == null || p.ParentProjectId == -1)
.Where(p => caller.IsAdmin || p.Owner!.Username == caller.Username || p.OwnerGroup!.Users.Contains(user));

query = query
.Include(static project => project.SubProjects)
.ThenInclude(static subProject => subProject.ProjectId);
var query = db.Projects
.Include(static project => project.Owner)
.Include(static project => project.OwnerGroup)
.Where(p => p.ParentProjectId == null || p.ParentProjectId == -1)
.Where(p => caller.IsAdmin || p.Owner!.Username == caller.Username || p.OwnerGroup!.Users.Contains(user));

query = query
.Include(static project => project.SubProjects)
.ThenInclude(static subProject => subProject.ProjectId);
The expression 'subProject.ProjectId' is invalid inside an 'Include' operation, since it does not represent a property access: 't => t.MyProperty'.
[Index(nameof(Name), IsUnique = true)]
public class Project
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProjectId { get; set; }

[Required]
[StringLength(100, MinimumLength = 1)]
public string Name { get; set; } = "";

[StringLength(200)]
public string Description { get; set; } = "";

public User? Owner { get; set; }
public int? OwnerId { get; set; }

public UserGroup? OwnerGroup { get; set; }
public int? OwnerGroupId { get; set; }

public Project? ParentProject { get; set; }
public int? ParentProjectId { get; set; }

public List<Pipeline> Pipelines { get; } = [];
public List<Keyword> Keywords { get; } = [];
public List<Project> SubProjects { get; } = [];
}
[Index(nameof(Name), IsUnique = true)]
public class Project
{
[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProjectId { get; set; }

[Required]
[StringLength(100, MinimumLength = 1)]
public string Name { get; set; } = "";

[StringLength(200)]
public string Description { get; set; } = "";

public User? Owner { get; set; }
public int? OwnerId { get; set; }

public UserGroup? OwnerGroup { get; set; }
public int? OwnerGroupId { get; set; }

public Project? ParentProject { get; set; }
public int? ParentProjectId { get; set; }

public List<Pipeline> Pipelines { get; } = [];
public List<Keyword> Keywords { get; } = [];
public List<Project> SubProjects { get; } = [];
}
How do I query a collection of projects, and only include the ID's of sub-projects instead of complete entities?
2 Replies
Jimmacle
Jimmacle6mo ago
with Select, not Include Include is for relationships, Select projects to a different structure
Denis
DenisOP6mo ago
hmmm, yeah I seem to have forgotten that Thanks!
Want results from more Discord servers?
Add your server