X

Like-operator in Entity Framework Core 2.0

Entity Framework Core 2.0 was announces yesterday and it brings some new and cool features. One of them is SQL Like-operator we can use now using directly in our code. Here is the simple web application that demonstrates using of new Like-operator.

Let’s start with simple Songs table in SQL Server database.

Here are the model for table and database context.

public class Song
{
    public int Id { get; set; }
    public string Artist { get; set; }
    public string Title { get; set; }
    public string Location { get; set; }
}

public class PlaylistContext : DbContext
{
    public PlaylistContext(DbContextOptions<PlaylistContext> options) : base(options)
    {
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Song>()
                    .HasKey(e => e.Id);

        base.OnModelCreating(modelBuilder);
    }

    public virtual DbSet<Song> Songs { get; set; }
}

I skip configuring database connection and all the stuff we need to do in Startup class as web is full of examples about these topics.

Let’s query out some songs from songs table in Home controller and let’s write the results out. Take a look at LINQ-query in Index method – this is where new Like-operator is used.

public class HomeController : Controller
{
    private readonly PlaylistContext _context;

    public HomeController(PlaylistContext context)
    {
        _context = context;
    }

    public IActionResult Index()
    {
        var query = from s in _context.Songs
                    where EF.Functions.Like(s.Title, "%angel%")
                    select s;
                       
        return View(query);
    }

    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
}

Index view needs also some changes to print out the list of songs found.

@model IEnumerable<Song>
@{

    ViewData["Title"] = "Angel songs";
}

<div class="row">
    <div class="col-md-4">
        <h2>Songs</h2>

        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>Artist</th>
                    <th>Title</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var song in Model)
                {
                    <tr>
                    <td>@song.Artist</td>
                    <td>@song.Title</td>
                    </tr>
                }
            </tbody>
        </table>
    </div>
</div>

Let’s run the application and see the output.

Here is the the SQL-query generated by Entity Framework Core 2.0. If you need to see SQL generated by EF then one quick option is described in blog post Entity Framework Core 2.0 Trace Strings.

SELECT [s].[Id], [s].[Artist], [s].[Location], [s].[Title]
FROM [Songs] AS [s]
WHERE [s].[Title] LIKE N'%angel%'

This is it. Like-operator works like charm and generated SQL looks also okay.

Wrapping up

Using Like-operator is made easy in Entity Framework Core 2.0. There is special functions class EF.Functions that provides us with Like-operator but there is not much more. I’m not sure what’s next but it seems like this class will be extended in future with additional methods that help us keep queries on LINQ level and avoid writing direct SQL.

Liked this post? Empower your friends by sharing it!

View Comments (6)

  • Hi, thanks for your post.

    How is this different from Linq **_context.Songs.Where(title=> title.Contains("angel")**

  • Hi!
    Thanks for question. s.Title.Contains("angel") translates to (CHARINDEX(N'angel', [s].[Title]) > 0). I guess it is handled different from LIKE operator.

  • @Jose The LIKE operator starts getting different when you use the placeholder "%" in other places than at the start and end of the term. E. g. LIKE 'dying%angel'

  • how do pass in a variable to the LIKE functions? I can't find anything online to help me.

    example:
    string query = "angel";
    EF.Functions.Like(s.Title, "%" + query + "%")

  • The rhyme vividly explains the act of hoping as a routine that connects these women to their traditions and beliefs, utilizing rich language and importance to communicate the power and significance of this technique in their every day lives. Among one of the most preferred quinceañera practices is the waltz, a classy, choreographed dance performed by the birthday lady and her court. They desired to select out garments for the lady they spend the majority of their time with and they desired to pay out the cash for it. The findings of surveys accomplished in Bolivia, Cuba, Colombia, El Salvador, Guatemala, Honduras, Nicaragua and the Dominican Republic reveal that male violence against females continues the day-to-days live of young people in Latin America. The poem "Latin Women Pray" by Judith Ortiz Cofer utilizes images, metaphor, and repeating to explore the cultural and spiritual relevance of hoping in Latin American ladies's lives. All throughout it. All Latin American countries seek sex equal rights. Latin society is abundant, diverse, and varies substantially across different nations and regions. The society of machismo prevailed in Latin America however in Europe ladies's suffrage movement was occurring.

    My culture shock triggered by his love of purchasing was absolutely nothing compared to the shock he experienced by my hatred of buying. LatamDate can have an appealing influence on the romance that starts online, so it's advised for love seekers. You can locate a single Latino looking for a day on any dating internet site. Countless Latin songs are trying to find foreign partners online, and over 2,000 regional women mosted likely to the USA utilizing their girlfriend visas last year. The web site Amor has a section specifically committed to San Francisco if one is looking for online meetups. There is a Latin online dating internet site called 'Migente.com' which is complimentary to join or there are the bigger companies like 'Match.com' and 'eharmony.com' that have certain nationality search options available. Women' Latin School of Baltimore was an university primary institution in Baltimore, Maryland, out there from 1890 to 1951. The school was founded in 1890 as an expansion of Goucher College, at the time situated on the school.

    In North American society, it is stereotyped for women to enjoy purchasing and guys to care much less regarding it. La Date: The go-to system for fulfilling your South American soulmate. I wish that this incredible online platform will aid me to locate that lady that intends to have a lovely latin dating with me. 9. Exactly how's the security of the Latin mail order bride-to-bes platform? Being a niche platform, the search pool is much smaller sized than on basic Latin Dating Sites. There are numerous various websites to pick from. There are some records of fake accounts, though, and some unethical billing practices. As soon as inside the criminal justice system, females remain to have an uniquely gendered experience, as they are overmuch subject to pre-trial latamdate scam detention and prolonged sentences-wreaking chaos on their family members and those that depend on them. Speak in English and trust the marked interpreter to translate words that you have to claim to the woman you are talking with. There are dating internet sites just for Latino's however. This agency possesses or more than likely partnered with a niche dating website.

    This website offers numerous communication tools, consisting of conversation and video phone calls, together with in-depth profiles to aid you locate a person who matches your preferences. Real-Time Messaging: Instant chat with suits, making interaction smooth. However do not be insecure with your conversation line phone dating partner. Latin Singles are on the internet now in our active area for Latino dating. Last but not least, our singles excursions put a whole lot of worth on the security of guests, staff, and the ladies going to the events. They can link you with Latino singles in your area. They have a broader customer base, and you can define what ethnic cultures you want. Unlike when travelling alone, you are guaranteed that the females you are meeting are of great criteria in both morals and looks. Whether Latin men choose to date African ladies now a days will depend upon the particular guy. These sites include, Latino People Meet, Latin America Cupid and a few others. Still, some websites enable it just when you and your interlocutor matched. Indulge in the magnificence of comfortable and fancy resort rooms while in the city and prepare on your own for the adventure ahead.

Related Post