How to perform a search in Entity Framework 6?

entity-framework

Question

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

1
10
12/12/2013 4:06:46 PM

Accepted Answer

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)))
11
7/21/2015 10:56:32 PM

Popular Answer

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').



Related Questions





Related

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