Duy Luân Duy Luân - 2 months ago 27
ASP.NET (C#) Question

Unable to retrieve metadata for models when adding a controller

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.

Answer

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; }
}