jeudi 7 avril 2016

Enum Condition in Linq Query in C#

I want to add Enum Condition in Linq Query even if Enum datamember is null or empty

I had added ALL in model for Filter purpose so that if user select ALL then all data should be displayed

Web Screen

Data Model :

    public partial class AuditTable
    {
        public int ID { get; set; }
        public int CompanyId { get; set; }
        public int KeyFieldID { get; set; }
        public System.DateTime DateTimeStamp { get; set; }
        public EntityType DataModel { get; set; }
        public string ValueBefore { get; set; }
        public string ValueAfter { get; set; }
        public string Changes { get; set; }
        public AuditActionType AuditActionTypeENUM { get; set; }

        public int EmployeeId { get; set; }
        public string EmployeeCode { get; set; }
        public string Remarks { get; set; }
        public string IPAddress { get; set; }
        public string UserName { get; set; }
    }
 public enum AuditActionType
    {
        All = 1,
        Create,
        Update,
        Delete
    }

    public enum EntityType
    {
        All = 1,
        BasicDetails,
        EmployeeDetails,
        PersonalDetails                
    }

Below code is working fine but had to repeat same query 4 times. I want to combine below query into one

if (eType == EntityType.All)
 if (aType == AuditActionType.All)
  AuditTrail = ent.tblAuditTable.Where(s => s.KeyFieldID == ID && s.EmployeeCode.Contains(code) && s.UserName.Contains(username)).OrderByDescending(s => s.DateTimeStamp).ToList(); 
 else
  AuditTrail = ent.tblAuditTable.Where(s => s.KeyFieldID == ID && s.AuditActionTypeENUM == aType && s.EmployeeCode.Contains(code) && s.UserName.Contains(username)).OrderByDescending(s => s.DateTimeStamp).ToList(); 
else
if (aType == AuditActionType.All)
 AuditTrail = ent.tblAuditTable.Where(s => s.KeyFieldID == ID && s.DataModel == eType && s.EmployeeCode.Contains(code) && s.UserName.Contains(username)).OrderByDescending(s => s.DateTimeStamp).ToList();
else
 AuditTrail = ent.tblAuditTable.Where(s => s.KeyFieldID == ID && s.AuditActionTypeENUM == aType && s.DataModel == eType && s.EmployeeCode.Contains(code) && s.UserName.Contains(username)).OrderByDescending(s => s.DateTimeStamp).ToList(); 

Aucun commentaire:

Enregistrer un commentaire