1

I'm learning ASP.NET MVC 5 on "Visual Studio 2015 Community" as a newbie. I'm trying to add a controller with Entity Framework models.

enter image description here

And an error appears. I'm so confused.

enter image description here

Here is my code:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;

namespace TwiApp.Models
{
    public class Twilio
    {
        [Key]
        public int id { get; set; }
        public string userId { get; set; }
        public string sid { get; set; }
        public string authToken { get; set; }
        public string fromNumber { get; set; }
        public string toNumber { get; set; }
        public bool status { get; set; }
        [ForeignKey("userId")]
        public virtual ApplicationUser twi_appuser_ref { get; set; }
    }
}

My connection string to SQL Server 2014:

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=TwiAppDB;Integrated Security=True"
  providerName="System.Data.SqlClient" />
</connectionStrings>

And finally, my databasecontext file:

using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
using TwiApp.Models;

namespace TwiApp.DAL
{
    public class DatabaseContext : IdentityDbContext<ApplicationUser>
    {
        public DatabaseContext() : base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public DbSet<Twilio> Twilio_Db { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {          
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            base.OnModelCreating(modelBuilder);
        }

        public static DatabaseContext Create()
        {
            return new DatabaseContext();
        }
    }
}

What I have tried so far:

  1. ASP.NET MVC/EF Code First error: Unable to retrieve metadata for model
  2. Unable to retrieve metadata - MVC application
  3. Unable to Retrieve Metadata
  4. MVC4 Scaffolding Add Controller gives error "Unable to retrieve metadata..."
  5. Cannot create controller with Entity framework - Unable to retrieve metadata for ' '

Any answers will be apprecited. Thank you.

Community
  • 1
  • 1
Luan Tran
  • 376
  • 1
  • 3
  • 15

6 Answers6

3

Try to update your Twilio Class like follow and EF will figure out the key and relation:

 public class Twilio
{
    //  [Key]
    public int Id { get; set; }
    public string sid { get; set; }
    public string authToken { get; set; }
    public string fromNumber { get; set; }
    public string toNumber { get; set; }
    public bool status { get; set; }
    //   [ForeignKey("userId")]
    public string userId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }
}
Abdul Hadi
  • 1,229
  • 1
  • 11
  • 20
  • I have just removed the [ForeignKey] attribute and it works. But how do I add the foreignkey into that class? – Luan Tran Sep 28 '16 at 11:38
  • You don't need to put key for class or ForeignKey EF will automatically figure out the key for class and when see ApplicationUser it will add the ForeignKey – Abdul Hadi Sep 28 '16 at 17:24
  • For those of us with a compulsion to do things explicitly: Instead of removing the ForeignKey reference, make sure it has a corresponding DbSet in your context class. – Bel Jul 27 '20 at 18:29
  • This is the correct answer. The virtual ApplicationUser property with the userId property, allows the framework by convention to add the foreignkey correctly. – António Godinho Dec 19 '20 at 18:40
2

This due to the Controller scaffolding is not properly recognizing connection string in web.config file.

In Web.config, set second providerName same as first providerName and after creating controller, undo that!

i.e

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=*.*.*.*;Database=database_name;uid=sa;pwd=******;" providerName="System.Data.SqlClient" /> 
</connectionStrings>

now revert back to original

<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=*.*.*.*;Database=database_name;uid=sa;pwd=******;" providerName="MySql.Data.MySqlClient" /> 
</connectionStrings>
Mannan Bahelim
  • 1,289
  • 1
  • 11
  • 31
1

In my case, the Data Context Class was missing some information. For anyone with this simple mistake:

  1. In the Data Context Class field, I selected the add button and made a new temporary DbContext. The 'retrieve metadata' error didn't pop up and the scaffold got created.
  2. Then I went into the newly created "temporary" DbContext and noticed some of the auto-generated DbSet methods were missing from my original DbContext. Added those into the original and retried creating scaffold and it worked.
H.B.
  • 55
  • 1
  • 8
  • This was the issue I had, though I did it more manually. Check to make sure that all of your ForeignKey references have a corresponding DbSet in your DbContext derived class. – Bel Jul 27 '20 at 18:25
1

you need to add opposite relation to create a controller like

ICollection<Twilio> twilio

in ApplicationUser class.

Usman
  • 121
  • 2
  • 6
0

MVC 5 / EF 6

perhaps you can do this in the older version?

  1. commented out the connection strings in the web / app.config then save
  2. have VS create a "new" dbcontext item instead of choosing the one you already have
  3. create
  4. delete new dbcontext class
  5. replace controller dbcontext with yours
  6. uncomment connection strings in web / app.config then save

worked for me!

Rick Penabella
  • 339
  • 2
  • 10
0

I think I just had this same error: enter image description here

The cause in my case was in my Part model:

public int OperationSetId { get; set; }
[ForeignKey("OperationSetId")]
public OperationSet OperationSet { get; set; }

Because I created my database using:

enable-migrations
add-migration initial
update-database

in the console, the tables in my IdentityModels.cs were not auto-generated for me(as they would have been if I ran my program).

To fix the error I inserted this line:

public DbSet<OperationSet> OperationSet { get; set; }

in my IdentityModels.cs at the very bottom of my ApplicationDbContext class

After adapted this code to your needs you will need to:

 add-migration migrationTitle
 update-database

in your console. Now you should be able to make the controller since your model is not referencing a non-existent table!