Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform a search in Entity Framework 6?

I have an entity "POST" on my context and the following:

String[] keywords = new String[] { "Car", "Yellow" };

How can I search all POSTS which title contains the 2 words?

NOTE: keywords can have 1 to 4 words.

The post entity is the following:

public class Post {
  public Int32 Id { get; set; }
  public DateTime Created { get; set; }
  public String Text { get; set; }
  public String Title { get; set; }
  public DateTime Updated { get; set; }
} // Post

And here is my SQL:

create table dbo.Posts
(
  Id int identity not null 
    constraint PK_Posts_Id primary key clustered (Id),
  Created datetime not null,
  [Text] nvarchar (max) not null,
  Title nvarchar (120) not null,
  Updated datetime not null
);

I have been looking at LIKE in SQL but what is the equivalent in Entity Framework?

Do I need Full Text Search? And is it available in SQL Server 2012 Express?

UPDATE

Following haim770 suggestion I tried the following:

Context context = new Context();
String[] words = new String[] { "Car" };
List<Post> posts = context.Posts.Where(x => words.Contains(x.Title).ToList();

No posts were returned with this ... Any idea?

Thank You, Miguel

like image 852
Miguel Moura Avatar asked Dec 12 '13 15:12

Miguel Moura


2 Answers

you may try this

var keywords = new String[] { "Car", "Yellow" }.ToList();

var p = db.Posts.Where(q => keywords.Any(k => q.Title.Contains(k)));

And, if you are looking for titles containing All words in the keyword list, then as you said:

var p = db.Posts.Where(q => keywords.All(k => q.Title.Contains(k)))
like image 117
Ahmad Ibrahim Avatar answered Jan 01 '23 23:01

Ahmad Ibrahim


Something like:

var keywords = new[] { "Car", "Yellow" };
var results = context.Posts.Where(x => keywords.Contains(x.Title));

The above will issue an SQL LIKE query.

If you want full-text search capabilities, first, you'll have to explicitly enable it in the database (you may have to install it if you're using the Express version), then use some solutions to integrate it with Entity Framework (probably using Entity Framdwork 6 'Interceptors').

like image 21
haim770 Avatar answered Jan 01 '23 23:01

haim770