我定義了以下物體:
public class Computer
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(15)]
public string Name { get; set; } = null!;
[Required]
public List<ComputerAction> Actions { get; set; } = new();
}
public abstract class ComputerAction
{
[Key]
public int Id { get; set; }
public List<HistoryEntry> History { get; set; } = new();
public Computer Computer { get; set; } = null!;
[NotMapped]
public Status Status => History.LastOrDefault()?.Status ?? Status.Unknown;
public abstract Task<HistoryEntry> ExecuteAsync();
}
public class RenewCertificateAction : ComputerAction
{
public override Task<HistoryEntry> ExecuteAsync()
{
// Whatever
}
}
public class PingAction : ComputerAction
{
private readonly Ping _ping = new();
public override async Task<HistoryEntry> ExecuteAsync()
{
// Whatever
}
}
public class HistoryEntry
{
[Key]
public int Id { get; set; }
[Required]
public Status Status { get; set; }
[Required]
public DateTime WhenExecuted { get; set; }
}
我的 DbContext 如下:
public class ComputerContext : DbContext
{
public ComputerContext(DbContextOptions<ComputerContext> options)
: base(options)
{
}
public static readonly string ComputerDb = nameof(ComputerDb);
public DbSet<Computer> Computers { get; set; } = null!;
public DbSet<RenewCertificateAction> RenewCertificateActions { get; set; } = null!;
public DbSet<PingAction> PingActions { get; set; } = null!;
public DbSet<HistoryEntry> History { get; set; } = null!;
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Computer>().HasMany(x => x.Actions).WithOne(x => x.Computer).OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<ComputerAction>().ToTable("ComputerActions").HasMany(x => x.History).WithOne().OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<HistoryEntry>().ToTable("ComputerActionEntries");
}
}
我想獲取所有計算機的串列,但如果它們碰巧有一個 type 的動作PingAction,那么還要加載那個動作(并且只有那個動作,而不是所有動作)。
對我來說合乎邏輯的是,dbContext.Computers.Include(x => x.Actions.OfType<PingAction>())但顯然不能轉化為查詢。我怎樣才能Include只做Actions一個特定型別的?
uj5u.com熱心網友回復:
你可以使用 where 里面包括:
dbContext.Computers.Include(x => x.Actions.Where(action => action is PingAction))
更多解釋:: https ://stackoverflow.com/a/61147681/11143288
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/426626.html
上一篇:C#物體框架。簡化查詢
