> посмотрите на комментарий @IvanStoev
даю возможность поиска для моегоMVC
EF
применение. Я создаю его с помощью динамического запроса. И следуя этому методуhttps://www.codeproject.com/Articles/493917/Dynamic-Querying-with-LINQ-to-Entities-and-Express
Его для создания предиката дляbool
а такжеstring
поля сущности. Основным объектом в моем приложении являетсяApplicant
EDMXApplicant
является следующее
public partial class Applicant
{
public Applicant()
{
this.ApplicantEducations = new HashSet<ApplicantEducation>();
this.ApplicantSkills = new HashSet<ApplicantSkill>();
this.Applications = new HashSet<Application>();
this.Experiences = new HashSet<Experience>();
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public byte[] CV_Upload1 { get; set; }
public string CV_Upload2 { get; set; }
public string email { get; set; }
public string password { get; set; }
public Nullable<System.DateTime> DOB { get; set; }
virtual ICollection<ApplicantEducation> ApplicantEducations { get; set; }
virtual ICollection<ApplicantSkill> ApplicantSkills { get; set; }
virtual ICollection<Application> Applications { get; set; }
virtual ICollection<Experience> Experiences { get; set; }
}
Я хочу выполнить поиск, например, по названию учебного заведения, которое указано в заявлении об образовании типа Институт. Кандидат может иметь один или несколько объектов ApplicantEducations.
Ниже приведен класс EDMX моего ApplicantEducations
public partial class ApplicantEducation
{
public int id { get; set; }
public Nullable<int> ApplicantId { get; set; }
public Nullable<int> InstituteId { get; set; }
public Nullable<int> EducationLevelId { get; set; }
public Nullable<bool> IsComplete { get; set; }
public Nullable<System.DateTime> DateStart { get; set; }
public Nullable<System.DateTime> DateEnd { get; set; }
public Nullable<short> GPA { get; set; }
public virtual EducationLevel EducationLevel { get; set; }
public virtual Institute Institute { get; set; }
public virtual Applicant Applicant { get; set; }
}
И мой класс сущности Института такой
public class Institute
{
public int Id { get; set; }
public string Name { get; set; }
}
Таким образом, пользователь будет искать, указав название института, и все кандидаты будут извлечены с образованием из этого института.
Как я уже упоминал выше, ссылка. Следующий пример демонстрируется для построения предиката строкового поля
private static Expression<Func<TDbType, bool>> ApplyStringCriterion<TDbType,
TSearchCriteria>(TSearchCriteria searchCriteria, PropertyInfo searchCriterionPropertyInfo,
Type dbType, MemberInfo dbFieldMemberInfo, Expression<Func<TDbType, bool>> predicate)
{
// Check if a search criterion was provided
var searchString = searchCriterionPropertyInfo.GetValue(searchCriteria) as string;
if (string.IsNullOrWhiteSpace(searchString))
{
return predicate;
}
// Then "and" it to the predicate.
// e.g. predicate = predicate.And(x => x.firstName.Contains(searchCriterion.FirstName)); ...
// Create an "x" as TDbType
var dbTypeParameter = Expression.Parameter(dbType, @"x");
// Get at x.firstName
var dbFieldMember = Expression.MakeMemberAccess(dbTypeParameter, dbFieldMemberInfo);
// Create the criterion as a constant
var criterionConstant = new Expression[] { Expression.Constant(searchString) };
// Create the MethodCallExpression like x.firstName.Contains(criterion)
var containsCall = Expression.Call(dbFieldMember, StringContainsMethod, criterionConstant);
// Create a lambda like x => x.firstName.Contains(criterion)
var lambda = Expression.Lambda(containsCall, dbTypeParameter) as Expression<Func<TDbType, bool>>;
// Apply!
return predicate.And(lambda);
}
приведенный выше код для построения предиката для простого строкового поля, содержащегося в основном классе сущностей (заявитель). Но у Кандидата также есть коллекция ApplicantEducation, поэтому мой вопрос заключается в том, как создать динамический запрос (предикат) для предложения where (метода) изlinq
поэтому, когда пользователь ищет название института, все кандидаты будут извлечены с одинаковым образованием.
Мои критерии поиска приведены ниже,
public class SearchCriteriaVM
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? DOB { get; set; }
public string Description { get; set; }
public ICollection<Models.ApplicantEducationVM> ApplicantEducations { get; set; }
public ICollection<Models.ExperienceVM> Experiences { get; set; }
public ICollection<Models.ApplicantSkillsVM> ApplicantSkills { get; set; }
public ICollection<Models.ApplicationsVM> Applications { get; set; }
}
Я немного растерян, как это возможно.
Спасибо