Recently I was working on one sample application with EFCodeFirst with the existing database.After doing all the coding I have found a error “Invalid object name ‘dbo.Customers’.”. Following was my code for data context.
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace CodeSimplified.Models { public class MyDataContext:DbContext { public DbSet Customer { get; set; } protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) { } } }
And following is code for my entity model class.
public class Customer { public int CustomerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public string City { get; set; } }
Once I run the application I was getting following error.
As you can see from my code that it should be dbo.customer name. So after digging into the issue I have found that I need to remove the plural table name. Here is a forum that is saying the same.
http://social.msdn.microsoft.com/Forums/en-ie/adonetefx/thread/719f3e4d-073b-49fe-9968-945acde27bb7.
Now there are two ways of resolving this issue. 1) Either explicitly map entity class with table attribute like I have changed my code like following.
[Table("Customer",SchemaName="dbo")] public class Customer { public int CustomerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Address { get; set; } public string City { get; set; } }
Another one is you need to remove default plural table name via overriding the onModelCreating event like following.
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Data.Entity.ModelConfiguration.Conventions.Edm.Db; namespace CodeSimplified.Models { public class MyDataContext:DbContext { public DbSet Customer { get; set; } protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder) { modelBuilder.Conventions.Remove(); } } }
That’s it now error is gone. My code is work perfectly!!. Hope this will help you.Stay tuned for more..Till that happy programming.