Created
April 21, 2017 09:16
-
-
Save rudiv/3aa3e1bb65b86ec78ec6f5620ee236ab to your computer and use it in GitHub Desktop.
EF Core .Include being ignored (no logged warning as expected if EF Core detects it)
This file contains hidden or 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 System.Linq; | |
namespace EFIncludeQueryable | |
{ | |
public class TestEntityA | |
{ | |
public int Id { get; set; } | |
public int TestEntityBId { get; set; } | |
public TestEntityB TestEntityB { get; set; } | |
public string BProperty { get { return TestEntityB.Property; } } | |
} | |
public class TestEntityB | |
{ | |
public int Id { get; set; } | |
public string Property { get; set; } | |
} | |
public class MyDbContext : DbContext | |
{ | |
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) | |
{ | |
optionsBuilder.UseSqlite("Data Source=testcase.db"); | |
} | |
public DbSet<TestEntityA> TestEntityAs { get; set; } | |
public DbSet<TestEntityB> TestEntityBs { get; set; } | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
using (var context = new MyDbContext()) | |
{ | |
context.Database.EnsureCreated(); | |
if (!context.TestEntityAs.Any()) | |
{ | |
context.TestEntityBs.Add(new TestEntityB { Property = "Hello World" }); | |
context.SaveChanges(); | |
context.TestEntityAs.Add(new TestEntityA { TestEntityBId = 1 }); | |
context.SaveChanges(); | |
} | |
} | |
// Works fine, .ToList() appears to be honouring .Include | |
using (var context = new MyDbContext()) | |
context.TestEntityAs.Include(m => m.TestEntityB).ToList().Any(m => m.BProperty == "Hello World"); | |
// Does not work, TestEntityB is null and so throws | |
using (var context = new MyDbContext()) | |
context.TestEntityAs.Include(m => m.TestEntityB).Any(m => m.BProperty == "Hello World"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment