Skip to content

Instantly share code, notes, and snippets.

@angelyordanov
Last active May 10, 2019 14:10
Show Gist options
  • Save angelyordanov/5feb7d2e91838db61d03ca8187da259e to your computer and use it in GitHub Desktop.
Save angelyordanov/5feb7d2e91838db61d03ca8187da259e to your computer and use it in GitHub Desktop.
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.DependencyInjection;
using System.Linq;
namespace FromSqlSample
{
class Program
{
static void Main(string[] args)
{
var services = new ServiceCollection();
services.AddEntityFrameworkSqlServer()
.AddDbContext<MyDbContext>(optionsBuilder =>
optionsBuilder
.UseSqlServer($"Server=localhost,1433;User Id=<user>;Password=<pass>;Initial Catalog=<db>")
.ConfigureWarnings(warnings =>
warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)));
var serviceProvider = services.BuildServiceProvider();
var dbContext = serviceProvider.GetService<MyDbContext>();
// succeeds
var res1 = dbContext.Query<UserQuery>()
.FromSql("SELECT\r\nEmail FROM Users")
.Where(u => u.Email == "test@gmail.com")
.ToList();
// throws an exception because local evaluation is disabled
var res2 = dbContext.Query<UserQuery>()
.FromSql("SELECT\nEmail FROM Users")
.Where(u => u.Email == "test@gmail.com")
.ToList();
}
}
class MyDbContext : DbContext
{
public MyDbContext(DbContextOptions<MyDbContext> options)
: base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Query<UserQuery>();
}
}
class UserQuery
{
public string Email { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment