Entity Framework Core 2.0 中使用LIKE 操作符

Entity Framework Core 2.0 中使用LIKE 操作符

不定时更新翻译系列,此系列更新毫无时间规律,文笔菜翻译菜求各位看官老爷们轻喷,如觉得我翻译有问题请挪步原博客地址

本博文翻译自:
http://gunnarpeipman.com/2017/08/ef-core-like-operator/

Entity Framework Core 2.0 早前发布,它带来了一些新的、很酷的特性。其中一个是SQL like操作符,我们现在可以直接在代码中使用它。下面是一个简单的web应用程序,它演示了使用新的like操作符。

我们先在SQL Server 数据库中建一个简单的歌曲表。

MSSQL: Songs table

下面是表和数据库上下文的模型。


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; }
}

我跳过配置数据库连接和在启动类中需要做的所有事情,因为网上有很多关于这些的例子。

让我们从主控制器的歌曲表中查询一些歌曲,让我们把结果写出来。看一下索引方法中的linq 查询这是使用新的like操作符的地方。


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 });
    }
}

索引视图还需要进行一些更改,以打印所找到的歌曲列表。


@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>

现在让我们运行程序看看它返回什么。

Entity Framework Core: Angel songs

下面是由Entity Framework Core 2.0生成的sql查询,如果您需要看到EF生成的SQL,请参考这篇博客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%'

这是它。like操作符好像十分有魅力,生成的SQL看起来也不错。

总结

在Entity Framework Core 2.0中使用like操作符很容易。有特殊的功能类EF.Functions。它为我们提供了同类型的运算符,但没有更多的功能。我不知道接下来会发生什么,但似乎这个类将会在以后扩展到其他的方法,这些方法可以帮助我们保持对LINQ级别的查询,避免编写直接的SQL。

欢迎转载,转载请注明翻译原文出处(本文章),原文出处(原博客地址),然后谢谢观看

如果觉得我的翻译对您有帮助,请点击推荐支持:)

posted @ 2017-09-07 21:24  东城慕水  阅读(841)  评论(3编辑  收藏  举报