Mixing Model first and Code first
We created a web application using the model first approach. A new developer came into the project and created a new custom model using the code first approach (using a database file). The
Here is the code first database context.
namespace WVITDB.DAL
{
public class DashboardContext : DbContext
{
public DbSet<CTOReview> CTOReviews { get; set; }
public DbSet<Concept> Concepts { get; set; }
//public DashboardContext()
// : base("name=DashboardContext")
//{
//}
// protected override void OnModelCreating(DbModelBuilder modelBuilder)
// {
// //modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
// }
}
}
The following controller method throws an error Could not find the conceptual model type for 'WVITDB.Models.FavoriteProject'.
and refers to the original database model. We are not sure开发者_Python百科 why (or how) it is calling that.
public ViewResult Index()
{
var d = db.Concepts.ToList(); //Throws error here
return View("Index",d);
}
When the DashboardContextclass is instantiated the error are shows up for both of the DBset properties.
Is there are a reason why the controller calling the wrong database?
EDIT:
FavoriteProject is in a different context (our main data model) and not related to the new custom model.
Found an answer, it maybe not what you want to hear though:
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/d2a07542-cb33-48ba-86ed-4fdc70fb3f1a
"If you are using the default code generation for the EDMX file then the generated classes contain a series of attributes to help EF find which class to use for each entity type. EF currently has a restriction that POCO classes can't be loaded from an assembly that contains classes with the EF attributes. (Short answer is no, your classes need to be in separate projects).
This is a somewhat artificial restriction and something that we realize is painful and will try and remove in the future."
So the workaround would be to split the classes into two different assemblies.
ajpaz - you may have to 'map' your existing model to the database table programatically. i'm assuming from the error message that its looking for the FavouriteProject table/class mapping. maybe the db has this defined as a singular, in which case try:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<FavouriteProjects>().ToTable("FavouriteProject");
}
you'd also need to do a dbset as per above (or some permutation of plurals):
public DbSet<FavouriteProjects> FavouriteProjects{ get; set; }
might be miles off, just a thought
[edit] - overiding your code 1st dbcontext in web.config (under connectionstrings [name MUST match your dbcontext name]):
<add name="DashboardContext" connectionString="Data Source=remote.sqlserver.server;Initial Catalog=code_first_db;Persist Security Info=True;MultipleActiveResultSets=True;User ID=code_first_db_user;Password=password" providerName="System.Data.SqlClient"/>
精彩评论