using System; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Linq; using CodeFirstStoreFunctions; namespace TestEntityFrameworkApp { class Program { static void Main(string[] args) { using (var ctx = new SampleDbContext()) { const string zipCode = "98052"; var q = ctx.CustomersByZipCode(zipCode) .Where(c => c.Name.Length > 3); //Console.WriteLine(((ObjectQuery)q).ToTraceString()); Console.WriteLine("TVF: CustomersByZipCode('{0}')", zipCode); foreach (var customer in q) { Console.WriteLine("Id: {0}, Name: {1}, ZipCode: {2}", customer.Id, customer.Name, customer.ZipCode, customer.Address); } } ; } } public class SampleDbContext : DbContext { public SampleDbContext() : base("name=SampleDBConnection") { this.Configuration.LazyLoadingEnabled = true; this.Configuration.ProxyCreationEnabled = true; } public DbSet Customers { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Add(new FunctionsConvention("dbo")); } [DbFunction("SampleDbContext", "CustomersByZipCode")] public IQueryable CustomersByZipCode(string zipCode) { var zipCodeParameter = zipCode != null ? new ObjectParameter("ZipCode", zipCode) : new ObjectParameter("ZipCode", typeof(string)); return ((IObjectContextAdapter)this).ObjectContext .CreateQuery( string.Format("[{0}].{1}", GetType().Name, "[CustomersByZipCode](@ZipCode)"), zipCodeParameter); } } public class Customer { public int Id { get; set; } public string Name { get; set; } public string ZipCode { get; set; } public Address Address { get; set; } } public class Address { public string Street { get; set; } public int Number { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public override string ToString() { return $"{Number} {Street}, {City}, {State}, {Country}"; } } }