不使用方法的賦值方式:
public UserAccountDTO GetUserAccountByEmployeeNo(string employeeNo) { if (!String.IsNullOrEmpty(employeeNo)) { var query = (from ua in clientDbContext.UserAccounts join e in clientDbContext.Employees on ua.fkEmployee equals e.pkEmployee where e.ID == employeeNo && (e.Status == null || e.Status != "Terminated") select new UserAccountDTO() { fkClient = ua.fkClient, pkUserAccount = ua.pkUserAccount, fkEmployee = ua.fkEmployee, UserName = ua.UserName, HashPassword = ua.HashPassword, SSOID = ua.SSOID, HasAcceptedTerms = ua.HasAcceptedTerms, IsAccountSuspended = ua.IsAccountSuspended, IsAccountLocked = ua.IsAccountLocked, AuthenticationMethod = ua.AuthenticationMethod, ID = e.ID, Role = ua.Role, InvalidAttempt = ua.InvalidAttempt, InvalidAttemptReset = ua.InvalidAttemptReset, LastPasswordChangedOn = ua.LastPasswordChangedOn, RequireChangePassword = ua.RequireChangePassword, ExpireOn = ua.ExpireOn, FullName = e.FullName, Email = e.Email, JobGrade = e.JobGrade, Avatar = ua.Avatar }); return query.FirstOrDefault(); } return null; }
將賦值提取為方法的寫法:
public virtual UserAccountDTO GetUserAccountByUserName(string userName) { if (!String.IsNullOrEmpty(userName)) { var query = (from ua in clientDbContext.UserAccounts join e in clientDbContext.Employees on ua.fkEmployee equals e.pkEmployee where ua.UserName == userName && (e.Status == null || e.Status != "Terminated") select new { ua,e }).AsEnumerable().Select(x=>MappinpData(x.ua,x.e));//先選取為匿名類X,再傳入方法 return query.FirstOrDefault(); } return null; } public UserAccountDTO MappinpData(UserAccount ua,Employee e) { return new UserAccountDTO() { fkClient = ua.fkClient, pkUserAccount = ua.pkUserAccount, fkEmployee = ua.fkEmployee, UserName = ua.UserName, HashPassword = ua.HashPassword, SSOID = ua.SSOID, HasAcceptedTerms = ua.HasAcceptedTerms, IsAccountSuspended = ua.IsAccountSuspended, IsAccountLocked = ua.IsAccountLocked, AuthenticationMethod = ua.AuthenticationMethod, ID = e.ID, Role = ua.Role, InvalidAttempt = ua.InvalidAttempt, InvalidAttemptReset = ua.InvalidAttemptReset, LastPasswordChangedOn = ua.LastPasswordChangedOn, RequireChangePassword = ua.RequireChangePassword, ExpireOn = ua.ExpireOn, FullName = e.FullName, Email = e.Email, JobGrade = e.JobGrade, Avatar = ua.Avatar }; }
例子:
public IEnumerable<Employee> GetEmployeeList(string searchKey) { var query = clientDbContext.Employees.Where(e => e.ID.Contains(searchKey) || e.FullName.Contains(searchKey)).AsEnumerable().Select(e => EntityCryption.Decrypt(e, entityCryptionKey)); return query; }