Created
July 25, 2012 04:23
-
-
Save mabster/3174380 to your computer and use it in GitHub Desktop.
Entity Framework and Interfaces
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 System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Data.Entity; | |
namespace ConsoleApplication5 | |
{ | |
public interface IFoo | |
{ | |
string Name { get; } | |
} | |
public class Foo : IFoo | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
public class MyContext : DbContext | |
{ | |
public MyContext() : base("server=.;database=blah;Integrated Security=True") | |
{ | |
} | |
public DbSet<Foo> Foos { get; set; } | |
} | |
public class ThingsWithNames<T> where T : IFoo | |
// THIS FIXES IT | |
// public class ThingsWithNames<T> where T : class, IFoo | |
{ | |
public IEnumerable<T> Get(IQueryable<T> items) | |
{ | |
return items.Where(i => i.Name != null); | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var ctx = new MyContext(); | |
// this works fine. | |
Func<IQueryable<IFoo>, IEnumerable<IFoo>> filter = items => items.Where(i => i.Name != null); | |
var foos1 = filter(ctx.Foos).ToList(); | |
// This throws: | |
// Unable to cast the type 'ConsoleApplication5.Foo' to type 'ConsoleApplication5.IFoo'. | |
// LINQ to Entities only supports casting Entity Data Model primitive types. | |
var foos2 = new ThingsWithNames<Foo>().Get(ctx.Foos).ToList(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternatively, you can download my project on Codeplex. I have a working example that you can copy.
https://entityinterfacegenerator.codeplex.com/
It generates the interface files that you need for IoC and unit testing purposes.