Tuesday, July 5, 2011

Invalid Object Name with Entity framework -EFCodeFirstCTP5

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> 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.

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> Customer { get; set; }

      protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
      {
          modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
      }
  }
}

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.

Shout it

kick it on DotNetKicks.com
Share:

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog

  

My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews