Entity Framework raises an exception: 'dbo.BaseCs' is an invalid object name.

asp.net-mvc-3 c# entity-framework sql

Question

Following Adam's advice in response to here, the Entity Framework now functions, and theSeed() method also functions.

But when I use the following method to access the database:

    public User FindUserByID(int id)
    {
        return (from item in this.Users
                where item.ID == id
                select item).SingleOrDefault();
    }
  .............................................................................
    // GET: /Main/

    public ActionResult Index(int? id)
    {
        var db = UserDataBaseDB.Create();

        if (!id.HasValue)
            id = 0;

        return View(db.FindUserByID(id.Value));
    }

An exception is thrown atreturn (from item in this.Users stating:

Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.BaseCs'.

I've attempted to replace it with:return this.Users.ElementAt(id); But after that, this exception is thrown.

LINQ to Entities does not recognize the method 'MySiteCreator.Models.User ElementAt[User](System.Linq.IQueryable It is not possible to convert the 1[MySiteCreator.Models.User], Int32)' function into a store expression.

Can somebody assist me?
I'm grateful.

1
46
1/29/2018 10:02:02 AM

Accepted Answer

Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.BaseCs'

Because of this issue, EF is converting your LINQ query into a SQL statement that utilizes an object (most likely a table) calleddbo.BaseCs which the database does not include.

Check your database to see whether that table is there or if an alternative table name should be used. Additionally, it would be easier to follow along if you included a link to the instruction you are using.

67
10/16/2011 1:18:21 PM

Popular Answer

As indicated by "adrift," the problem most likely results from a naming conflict between the model class and the table name. When you wish to keep the model class name distinct from the table name, make these the same or use the example below (that I did for OAuthMembership). Keep in mind that the table name is webpages OAuthMembership whereas the model class name is OAuthMembership.

Either give the Model a table attribute:

[Table("webpages_OAuthMembership")]
public class OAuthMembership

OR make the mapping available by replacing DBContext OnModelCreating:

class webpages_OAuthMembershipEntities : DbContext
{
    protected override void OnModelCreating( DbModelBuilder modelBuilder )
    {
        var config = modelBuilder.Entity<OAuthMembership>();
        config.ToTable( "webpages_OAuthMembership" );            
    }
    public DbSet<OAuthMembership> OAuthMemberships { get; set; }        
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow