首页 > 解决方案 > 如何在 EF Core 5 请求中使用未映射的属性

问题描述

我需要在代码中的许多地方使用一种条件(前端也是如此)。我保持这种情况就像模型中的属性一样。问题是将此属性用于 EF 核心请求,因为无法翻译。

简化示例(实际情况更复杂):

public class Job
{
  public DateTime? StartTime{get;set;}
  public DateTime? EndTime{get;set;}
  public bool Enabled{get;set;}

  public bool IsRunning
  {
    get{ return !EndTime.HasValue && Enabled }
  }
}

public class Repository
{
 public List<Job> GetRunningJobs
 {
  _context.Jobs.Where(j => j.IsRunning).ToList();
 }
}

最好的方法是什么?谢谢

标签: c#ef-core-5.0

解决方案


你必须写好你的linq查询

public class Repository
{
 public List<Job> GetRunningJobs()
 {
     using(AppContext _context = new AppContext())
     {
       
        return _context.Jobs.Where(j => j.IsRunning == true && j.EndTime != null )
                            .ToList();
     }
 }
}

另一种方法是你可以有另一个类,即 JobDto(数据传输对象)

public class JobDto 
{ 
      public DateTime? EndTime{get;set;}
      public bool Enabled{get;set;} 
}
public class Repository
{
 public List<JobDto > GetRunningJobs()
 {
     using(AppContext _context = new AppContext())
     {
         IQueryable<JobDto> list;
                    list = from i in appContext.Jobs
                           where i.IsDeleted == null
                           && u.IsRunning == true
                           && u.EndTime != null
                           select new JobDto (){
                             EndTime= i.EndTime//set other stuff
                           };

                return list.ToList();
     }
 }
}

推荐阅读