How to perform a search in Entity Framework 6?



I have the following in my context along with an entity named "POST":

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

How can I find all posts with those two terms in the title?

NOTE: A keyword may contain one to four words.

The following describes the post entity:

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 now for 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've been examining LIKE in SQL, but what does Entity Framework's counterpart look like?

Is Full Text Search necessary? And does SQL Server 2012 Express support it?


As suggested by haim770, 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();

This did not return any posts. Any ideas?

I'm grateful. Miguel

12/12/2013 4:06:46 PM

Accepted Answer

Try this, you might

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

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

Additionally, as you mentioned, if you're looking for books with the phrases "All" in the title, then

var p = db.Posts.Where(q => keywords.All(k => q.Title.Contains(k)))
7/21/2015 10:56:32 PM

Popular Answer

the following

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

The previous will generate a SQLLIKE query.

First, you'll need to manually enable full-text search in the database (you might need to install it if you're using the Express version), then utilize various solutions to integrate it with Entity Framework (possibly using Entity Framework 6 "Interceptors").

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow