簡體   English   中英

如何在 EF Core 5 請求中使用未映射的屬性

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

我需要在代碼中的許多地方使用一種條件(前端也是如此)。 我在 model 中保持這種情況。 問題是將此屬性用於 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();
 }
}

最好的方法是什么? 謝謝

你必須寫好你的 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();
     }
 }
}

另一種方法是您可以擁有另一個 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();
     }
 }
}

感謝大家的幫助。 我以這種方式使用了提到的規范模式:

 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