简体   繁体   English

如何在 EF Core 5 请求中使用未映射的属性

[英]How to use not mapped properties in EF core 5 request

I need to use one condition in many places in code (frontend as well).我需要在代码中的许多地方使用一种条件(前端也是如此)。 I keep this condition like property in model.我在 model 中保持这种情况。 Problem is use this property for EF core request, becouse could not be translated.问题是将此属性用于 EF 核心请求,因为无法翻译。

Simplified example (real condition is more complex):简化示例(实际情况更复杂):

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

What is the best approach?最好的方法是什么? Thank you谢谢

you have to write your linq query well你必须写好你的 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();
     }
 }
}

the other way is you can have another class ie JobDto (Data Transfer Object)另一种方法是您可以拥有另一个 class 即 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();
     }
 }
}

Thanks to all for your help.感谢大家的帮助。 I used mentioned Specification pattern in this way:我以这种方式使用了提到的规范模式:

 public abstract class Specification<T>
    {
      public abstract Expression<Func<T, bool>> ToExpression();    
      public bool IsSatisfiedBy(T entity)
      {
        Func<T, bool> predicate = ToExpression().Compile();
        return predicate(entity);
      }
    }

    public class RunningJobSpecification : Specification<Db.JobSetting>
    {
      public override Expression<Func<JobSetting, bool>> ToExpression()
      {
        return job => !EndTime.HasValue && Enabled;
      }
    }

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

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

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