Infrastucture does not exist in System.Data.Entity - c#

I am trying to create MVC project with Entity Framework.
I have 3 Projects in Solution
SerialTracker.Common
SerialTracker.Model
SerialTracker.Web
Common and Model are compiled like library, so Web is using them.
Model is also using Common.
My probelm is here:
Model generate from *.edmx ==> *.Context.tt ==> whitch auto generates *.Context.cs:
namespace SerialTracker.Model
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class SerialTrackerEntities : DbContext
{
public SerialTrackerEntities()
: base("name=SerialTrackerEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Role> Role { get; set; }
public DbSet<User> User { get; set; }
}
}
I have error, that Infrastucture does not exist in System.Data.Entity. I tried adding some References, but i think the problem is in another place.
//EDIT:
I reinstaled NuGet package for this project, but now i have error and doesn't exist
Sorry for my poor English.

S̶o̶ ̶I̶ ̶m̶a̶n̶u̶a̶l̶y̶ ̶a̶d̶d̶e̶d̶ ̶f̶i̶l̶e̶ ̶S̶e̶r̶i̶a̶l̶T̶r̶a̶c̶k̶e̶r̶.̶t̶t̶ ̶t̶o̶ ̶S̶e̶r̶i̶a̶l̶T̶r̶a̶c̶k̶e̶r̶.̶e̶d̶m̶x̶.̶
T̶h̶i̶s̶ ̶f̶i̶l̶e̶ ̶I̶ ̶c̶o̶p̶i̶e̶d̶ ̶f̶r̶o̶m̶ ̶a̶n̶o̶t̶h̶e̶r̶ ̶p̶r̶o̶j̶e̶c̶t̶.̶
N̶o̶w̶ ̶i̶s̶ ̶p̶r̶o̶j̶e̶c̶t̶ ̶g̶e̶n̶e̶r̶a̶t̶e̶ ̶e̶n̶t̶i̶t̶i̶e̶s̶ ̶R̶i̶g̶h̶t̶.̶
EDIT (04-29-2014):
Renewed answer:
You can delete file *.tt and recreate it with
Add -> New Item -> EF 5.x DbContextGenerator (or EF 6.x ...)

Related

Schema specified is not valid exception occured when using table in multiple dlls

I have an issue as described here. Let me explain the details.
I have a table which is used for two different dll's with different edmx files. And I have an executable which uses these two dlls. When I call one of them, it throws the exception specified in the above(Schema specified is not valid, multiple types with the name...)
Can someone describe me what causes this error in this case?
Edit: Detailed explanation is below:
Below code is in ABC.dll:
ABC.dll -> EntModel.edmx -> EntModel.Context.cs
namespace MyNamespaceABC
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class AbcEntities : DbContext
{
public AbcEntities()
: base("name=AbcEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<MyTable> MyTables { get; set; }
}
}
Below code is in XYZ.dll:
XYZ.dll -> EntModel.edmx -> EntModel.Context.cs
namespace MyNamespaceXYZ
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class XyzEntities : DbContext
{
public XyzEntities()
: base("name=XyzEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<MyTable> MyTables { get; set; }
}
}
And these dlls are used by an executable called Main.exe. When I test these dlls on their tester projects, they work like a charm. Then, when I call it from Main.exe, both of the dlls throw this exception when I try to retrieve data.
Schema specified is not valid. Errors:
Multiple types with the name 'MyTable' exist in the
EdmItemCollection in different namespaces. Convention based mapping
requires unique names without regard to namespace in the
EdmItemCollection.
To resolve this issue, I renamed the entity name in the edmx diagram and the error is gone.
To sum up, it is forbidden to use same entity name for different projects. Using one and only structure for accessing database will resolve the issue permanently for the main project.

How to know project is code-first or database-first?

In an existing project, how do I know if it's code-first or database-first?
Project has this lines of code:
public class TestDBContext : DbContext
{
public DbSet<Player> Players { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
And project has no .edmx file. If any other details need I will share.
EDIT:
Player.cs class
public class Player
{
public int PlayerID { get; set; }
public string PlayerName { get; set; }
}
EDIT 12.05.2017
IF I change database name from connection string and run project, it creates database with the new name with all tables. May be this will be hit for the answer.
If this is a project is Database-first, there is :
[name].edmx diagram file and with it, [name].Context.tt & .cs
every tables that are translated into class are hidden in tree like .edmx > .tt
in OnModelCreating, there is a throw new UnintentionalCodeFirstException()
If not, all the class issue from the tables are in the project (no tree).
Here I am sharing my observation.
Mainly there are two approaches to implement Entity Framework.
1. Code-first
If chosen, it will create simple .cs file(s) which developers later modifies as per their requirement.
Data-first
If chosen, it will create a [name].edmx file along with hierarchy of different files. It contains .Context.tt and underneath .Context.cs file.
The .Context.cs file will have below snippet which indicates whether induced entity model was empty when created or it was with any database object.
namespace Search
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class XYZ_MSCRMEntities : DbContext
{
public XYZ_MSCRMEntities()
: base("name=xyz_MSCRMEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<AnyDatabaseTableOrView> TableOrViewPluralized { get; set; }
}}
In above snippet, very last line (DbSet property) shows that it has imported database object and that is how it is "Data-first"
If there is no .edmx file, the project is code-first.

How do I get Entity Framework Code First Migrations to see my models?

I made a new ASP.Net Web Application and enabled migrations on it. I ran add-migration initial and the initial migration does in fact have all the default tables for authentication (dbo.AspNetRoles, dbo.AspNetUserRoles, etc). However, when I create my own context and add an entity model to it, I can't get migrations to acknowledge that model. That is, when I run add-migration added-watchedgame-model I just get an "empty" migration file. So what am I doing wrong? Does my DbContext have to be referenced somehow? can Entity Framework only handle migrations for 1 dbcontext?
ReleaseDateMailerDBContext.cs:
using System.Data.Entity;
using WebApplication4.Models;
namespace WebApplication4.DataAccess
{
public class ReleaseDateMailerDBContext : DbContext
{
public ReleaseDateMailerDBContext() : base("DefaultConnection") { }
public DbSet<WatchedGameModel> WatchedGameModelSet { get; set; }
}
}
WatchedGameModel.cs:
using System.ComponentModel.DataAnnotations;
namespace WebApplication4.Models
{
public class WatchedGameModel
{
public int ID { get; set; }
[MaxLength(1024)]
public string URL { get; set; }
public string Email { get; set; }
public bool EmailSent { get; set; }
}
}
"empty" migration file:
namespace ReleaseDateMailer.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class addedwatchedgamemodel : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
"Batch Clean" may resolve your porblem.
It suggests that the EF tooling/assemblies are looking in a location other than the default build output location (typically /bin/Debug). The clean command also, incidentally, clears intermediary outputs.
To do a batch clean:
Select Build -> Batch Build
Click Select All
Click Clean
Close dialog, rebuild and re-attempt migration.
While running the add-migration command your package manager console should be pointed to the project having your DBContext class (WebApplication4.DataAccess).
If you have migration in a different project than your web application project (suppose WebApplication4.Web) then you should run the following command:
add-migration "MigrationName" -projectName:WebApplication.DataAccess -startupProjectName:WebApplication4.Web
Hope it helps!!
With the built-in asp.net mvc project, a DbContext class (ApplicationDbContext) is already
created!
When you enter enable-migrations, a migration configuration class is created based on the dbcontext class that it finds.
When you enter add-migration "migrationname", That dbcontext class is what is checked for differences.
So all one has to do is, rather than making one's own class that derives from DbContext, use that one.

Entity framework standalone project vs entity set within main project

There seems to be something strange happening with regards to adding an entity set to an existing project vs having an entity set in its own project for re-usability.
Scenario One
Project A is a class library and has an EF set added to it and connected to a database.
Within the default class in the class library project, this code is written and compiles fine.
public void test()
{
using (var context = new Accu_CRM_dbEntities())
{
var test = context.BillableParts.First(P => P.Id == "test");
}
}
Scenario Two
Project B is another project added to the same solution. A reference is made to project A so as to use the identities in project B. A using statement is placed in the code file that is going to be making dB calls with the EF set. The same code is written into project B; however, the compiler complains that 'DAL.Accu_CRM_dbEntities': type used in a using statement must be implicitly convertible to 'System.IDisposable'. Aside from this, all intellisense support is lost when dealing with the context.
If I type context.BillableParts. intellisense support ceases after the entity name. What exactly is the reason that project B cannot see that Accu_CM_dbEntities should be disposable the way it is in project A?
namespace DAL
{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class Accu_CRM_dbEntities : DbContext
{
public Accu_CRM_dbEntities()
: base("name=Accu_CRM_dbEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public virtual DbSet<BillablePart> BillableParts { get; set; }
public virtual DbSet<BillableService> BillableServices { get; set; }
public virtual DbSet<Customer> Customers { get; set; }
public virtual DbSet<Part> Parts { get; set; }
public virtual DbSet<PartsManufacturer> PartsManufacturers { get; set; }
public virtual DbSet<WorkOrder> WorkOrders { get; set; }
}
}
Perhaps some more information on the database would have been a bit more useful. I am using SQL server compact. I used nuget and installed EF for sql compact within my consuming project (consumer of EF project) and everything was fixed. I am not 100% sure what was the issue exactly but obviously I did not have the correct libraries referenced. I'll leave this up here for anyone else that might be getting this error

How to Enable Migration to update my database in MVC4?

I'm working on a project using MVC4 in Visual Studio 2012 and have added a column in the table.
Now when I want to debug my project the error says to use the migration to update my database.
What I have to do?
I have been searching a lot and found some methods like:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<ResTabelaIndex>(null);
}
but don't know how and where to implement this... Have tried in app_start, global.asax etc...
What I found was, to enable the migrations directly in the console from the nuget.
But I can't make this work.
Commands I use:
Enable-Migrations -EnableAutomaticMigrations
==> Console says that more than one context was found .
To enable use, Enable-Migrations -ContextTypeName NameOfTheNamespace.Models.DefaultConnection
But I don't know what is the -ContextTypeName, have tried a lot but couldn't understand.
My Model Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Data.Entity.Migrations;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Infrastructure;
namespace Vista.Models
{
public class TabelaIndex
{
public int ID { get; set; }
public string n_empresa { get; set; }
public string titulo{ get; set; }
public string url { get; set; }
public string imagens { get; set; }
}
public class DefaultConnection : DbContext
{
public DbSet<TabelaIndex> ResTabelaIndex { get; set; }
}
}
Commands:
enable-migrations default context
add-migration InitialCreate (for generating snapshot)
add-migration InitialCreate (to apply snapshot)
update-database
update-database -verbose
Detailed explination will here:
http://www.dotnet-tricks.com/Tutorial/entityframework/R54K181213-Understanding-Entity-Framework-Code-First-Migrations.html
The error is saying that you have two contexts. When you first create a project using MVC 4, Visual Studio creates a context for your SimpleMembership by default (check Models/Account.cs) or do a ctrl+f for UsersContext, you can just delete this file if you are not using SimpleMembership.
After removing this context, go ahead and add the following to your DefaultConnection class:
protected override void OnModelCreating(DbModelBuilder builder)
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<DefaultConnection,Configuration>());
}
If you enabled migrations correctly you should also have a folder called Migrations and inside it a Configuration class, its constructor should look like this (if you want to enable automatic migrations):
public Configuration()
{
AutomaticMigrationsEnabled = true;
}
Try typing this into the console:
Enable-Migrations -ContextTypeName Vista.Models.DefaultConnection
Vista.Models.DefaultConnection is your context (the class that inherits from DbContext).
If you have small changes not need migration. You can add column to any table on database with sql script and add property to model and delete metadata table. (back up database firstly no doubt).
Or you can use Migrations like this: aspnet-mvc-4-entity-framework-scaffolding-and-migrations

Categories