Question

I´m try to implement a search for my database who is searching in a lot of columns. For the output i want to sort the results about how often the search value is appear in different coumns.

For example i have a query like:

from model in dataContext.Models
where model.Name.Equals(value) || model.Description.Contains(Value)
select model

is it possible to add a variable, maybe in the entity, that store a counter who is count +1 for each true where clause.

In the example, if the value test is in model.Name and model.Description i would have a count of 2 if only in model.Name it´s 1 and so on.

So in simple c# it would be doing the work of this method:

public List<Object> GetAllModelsWithValue(string value)
{
    List<Object> Models = new List<Object>();
    forach(var model in dataContext.Models)
    {
        var count =0;
        var modelCorrect = false;
        if( model.Name.Equals(value))
        {
            count =+1;
            modelCorrect = true;
        }
        if(model.Description.Contains(Value))
        {
            count =+1;
            modelCorrect = true;
        }
        if(modelCorrect )
        {
            Models.Add(new{model,count});
        }
    return Models;
}

The exact model seems not to be relevant for the question. We can imagine a model like:

[Table(Name = "Model")]
public class Model
{
    [Column(Name = "Model_ID", IsPrimaryKey = true, IsDbGenerated = true, AutoSync =  AutoSync.OnInsert)]
    public int Id { get; set; }
    [Column(Name = "Model_Name", CanBeNull = false)]
    public string Name { get; set; }
    [Column(Name = "Model_Description", CanBeNull = true)]
    public string Description { get; set; }
}

An search outside sql will slow down the search a lot, so my idea was to bring the search in the sql.

Was it helpful?

Solution

What about creating new type including information about matches? For example:

from model in dc.Models
where model.Name.Equals(value) || model.Description.Contains(value)
select new ModelMatches
{
    Matches = (model.Name.Equals(value) ? 1 : 0) + (model.Description.Contains(value) ? 1 : 0),
    Model = model
};

public class ModelMatches
{
    public Model Model { get; set; }
    public int Matches { get; set; }
}

Or if you need to identify WHICH columns matched, you could calculate some bit mask based on matches.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top