Last active
May 10, 2019 14:10
-
-
Save angelyordanov/5feb7d2e91838db61d03ca8187da259e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 == "[email protected]") | |
.ToList(); | |
// throws an exception because local evaluation is disabled | |
var res2 = dbContext.Query<UserQuery>() | |
.FromSql("SELECT\nEmail FROM Users") | |
.Where(u => u.Email == "[email protected]") | |
.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