MVC 3 Creates a new database instead of using the one specified - asp.net-mvc-3

I'm creating a new MVC 3 pilot application using Mvc3 and the MvcScaffolding NuGet, everything runs smoothly until i want to use the database i already have. The application keeps creating a database with the format:
projectname.Models.projectnameContext
I'm stuck in here, my connectionStrings is:
<connectionStrings>
<add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" providerName="System.Data.SqlClient" />
<add name="EnginesTrackingEntities" connectionString="metadata=res://*/Models.Model1.csdl|res://*/Models.Model1.ssdl|res://*/Models.Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=WARCHLAPPY\SQLEXPRESS;initial catalog=[EnginesTracking];integrated security=True;multipleactiveresultsets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
In which specifies that my database is EnginesTracking.
Update
I'm following the database first approach from this example.
I have everything working perfectly but when the application starts, it creates a new table instead of using the one i specified.
The only one difference is that there is no databaseEntities in my project, instead there is projectContext for which i cannot do the number 8 step
Update2
I'm kinda given up on this, going to follow codeFirst approach as this is taking to much time for only being a pilot.
This is the Model1.context.cs:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ErrorReportingSystem.Models{
using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
public partial class EnginesTrackingEntities : DbContext
{
public EnginesTrackingEntities()
: base("name=EnginesTrackingEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<Engine_Part> Engine_Part { get; set; }
public DbSet<Engines> Engines { get; set; }
public DbSet<Error> Error { get; set; }
public DbSet<Has_error> Has_error { get; set; }
public DbSet<Locations> Locations { get; set; }
public DbSet<Operators> Operators { get; set; }
public DbSet<sysdiagrams> sysdiagrams { get; set; }
}
}

I finally found the problem. I found a similar issue here which finished pointing me in the right direction.
I had to add:
public ErrorReportingSystemContext() : base("name=EnginesTrackingEntities") { }
To the ErrorReportingSystemContext.cs file under /Models folder.
Done!

Seems like you are using Code First Entity Framework. The post will probably get the best exposure in that forum. EnginesTrackingEntities is an EF connect string.
One of the big problems in dealing with code-first is the db drop and re-create with every change to your POCO's.
I strongly prefer database first approach because it is not as hard to deploy (not hard at all) and where you are pointing is clear. The advantage of code first is being able to elegantly style and decorate your POCO's.
I'm not exactly answering your question due to lack of info, but helping direct you. With a little more info on your deployment and Entities, I may be able to help more.

Related

Why am I getting "Type does not exist" error adding a new razor page using entity framework

I am experimenting with Visual Studio 2022 and EF Core 6. I created a solution with three projects, one with my razor pages one with my dbcontext and one with my entity. I was able to get the migration working with no issue, creating the database and single table which to me indicates I have everything working properly, but when I go to add a razor page and allow VS to wire up a "List" template for me, it spins for a minute and gives me an error: A type with the name Scaffolding.Entities.EncylopediaEntry does not exist.
Here is the class that apparently doesn't exist
using System.ComponentModel.DataAnnotations;
namespace Scaffolding.Entitites
{
public class EncylopediaEntry
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
}
And here is the DbContext with a hard coded connection string for now as I'm trying to figure out why scaffolding isn't working
using Microsoft.EntityFrameworkCore;
using Scaffolding.Entitites;
namespace ScaffoldingTest.Data
{
public class ScaffoldingContext : DbContext
{
public DbSet<EncylopediaEntry> encyclopediaEntries { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("{remove}");
}
}
}
I'd got same error. Visual Studio 2022 (preview too) with NET 6.0.
I installed NET 5.0 and tested with new project net 5 then works well.
But not with NET 6.0.

Entity Framework, Ninject dependency injection, and ASP.NET MVC 3, with existing .MDF file as database

I'm making a long and detailed post here, but I sincerely believe it's better to provide as much info up front. If any further clarification is needed, please ask. My heartfelt thanks to you for reading my query.
I'm using the book Pro ASP.NET MVC3 Framework by Adam Freeman and Steven Sanderson (Apress, Third Edition), and working through the Sports Store example beginning with Chapter VII. Note that the project entails the use of DI through the use of Ninject, and this is the main reason I wanted to take the time for this walkthrough. Another impressive contribution in this tutorial is the fact that it shows you how to develop an MVC 3 solution into separate projects the way it might be done in in a real world implementation--a thing I've found to be lacking in just about every other book I've ever looked at. (BTW I think the Apress books are just about the best ones out there, generally speaking.)
OK, so I've worked through Chapter 7 and well into Chapter 8, which means that I've successfully created and populated a database and retrieved its contents to appear in my List view. I've also gotten the formatting to work through the .css file. However, there's a catch here: When going through this the first time, I created the database from the IDE itself, which was no problem because there's only one small table (Products) to worry about. Everything was working fine. But then, for reasons I will shortly make clear, I decided to start over. This time, I wanted to follow through the same walkthrough with the exception that I would access the data by attaching to an existing .MDF file rather than creating a new DB from scratch as I coded the project. All this is to pave the way for me to use a similar pattern for my real project, for which I already have built a complex DB, replete with tables, FK relationships, views, functions--and data. I hardly need to say that I want to use my existing database in my "real" project, because recreating all that from scratch would be virtually impossible.
OK, now let's return to the Sports Store example. Try as I might, I cannot get the data from the database to my UI view. There are no error messages at compile time or run time, but instead of seeing the data in the List view, I see nothing but a blank page. Note that in this case it's correct in that there are no column headings or panes because there isn't any scaffolding here.
As far as I can see I have all the parts I need. Let's begin with the Ninject controller factory:
NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override
IController GetControllerInstance
(RequestContext requestContext, Type controllerType)
{
return controllerType == null ? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
//Had the mockup here before, which worked fine.
ninjectKernel.Bind<IProductRepository>().To<SportsStore2.Domain.Concrete.EFProductRepository>();
} ...
}
IProductRepository is as follows:
namespace SportsStore2.Domain.Abstract
{
public interface IProductRepository
{
IQueryable<Product> Products { get; }
}
}
And EFProductRepository is implemented thus:
namespace SportsStore2.Domain.Concrete
{
public class EFProductRepository:IProductRepository
{
private EFDbContext context = new EFDbContext();
public IQueryable<Product> Products
{
get { return context.Products; }
}
}
}
Why yes, of course EFDbContext is defined; viz the declaration:
namespace SportsStore2.Domain.Concrete
{
class EFDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
}
And the connection string in Web.config file; this is supposed to wire up the context object definition with the actual database in the .MDF file, at least as I understand it.
<connectionStrings>
<add name="EFDbContext"
connectionString="Data Source=Owner-PC\SQLEXPRESS;Initial Catalog = SportsStore20130205; Integrated security=SSPI"
providerName="System.Data.SqlClient" />
</connectionStrings>
Last and almost certainly least, I have the Product controller defined as follows. I say "least" because I'm almost positive the problem isn't here. In Debug mode, I can tell that the productRepository object isn't being populated. I can see some SQL code in there which is supposed to be run, or have been run by this point. But the invocation of repository.Products returns nothing.
namespace SportsStore2.WebUI.Controllers
{
public class ProductController : Controller
{
private IProductRepository repository;
public ProductController(IProductRepository productRepository)
{
repository = productRepository;
}
public ViewResult List()
{
return View(repository.Products);
}
public ViewResult Count()
{
int counter = repository.Products.Count();
return View(repository.Products.Count());
}
}
}
namespace SportsStore2.WebUI.Controllers
{
public class ProductController : Controller
{
private IProductRepository repository;
public ProductController(IProductRepository productRepository)
{
repository = productRepository;
}
public ViewResult List()
{
return View(repository.Products);
}
}
}

ASP.NET MVC3 Validation error

If you go to this website, http://www.asp.net/mvc/tutorials/getting-started-with-aspnet-mvc3/cs/intro-to-aspnet-mvc-3, you can see a tutorial where users create a movie database. I completed this tutorial with no problems, and attempted to create a new MVC application with some small changes that make the project more similar to what I want to do eventually.
Rather that create a model named Movie, I created one named Issue. Like movie, it has a few fields, but they are all different names and types. I went through the process exactly as is done in the tutorial, but whenever I try to add an issue to the database via the web UI, I get a DBEntityValidationException. I have not set any validation rules at this point in the process, so I am unsure of what the problem is.
Can someone give me some advice on fixing this so that I can add Issues to my database (as is done with movies on the online tutorial)?
Let me know if more information is needed; I am very new to this and may be lacking in details.
Here is the model code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcApplication200.Models
{
public class Issue
{
public String id { get; set; }
public DateTime created { get; set; }
public DateTime closed { get; set; }
public String summary { get; set; }
public bool? importToTFS { get; set; }
}
public class IssueDBContext : DbContext
{
public DbSet<Issue> Issues { get; set; }
}
}
Update:I just redid the whole process, but rather than have different fields and different types, I made it so that my Issue model had the same number and same types of fields (with only different names). The error went away, so the problem must be with db format or something. I hope this makes the problem more clear.
I just ended up adding this class, which removes everything from the database when fields are changed. Then, I refresh the database, which is easy to do in my situation. One could add some items to the Seed method in order to ensure that some things remain in the updated database after it is cleared.
public class IssueInitializer : DropCreateDatabaseIfModelChanges<IssueDBContext>
{
protected override void Seed(IssueDBContext context)
{
//add things here
}
}

Entity framework 4.1 won't connect to SQL Server after using Database First approach

I've created a new MVC 3 website using EF 4.1 with DB first approach. I've created the edmx file and then the DBContext (the new 4.1 feature) classes. all went well.
Then, I've created new controllers using the automatic creation for DBContext. All wen't great.
Now, that I'm trying to fire up the website it won't connect to the connection string itself created.
Here is the connection string:
<add name="PizzaByMeEntities"
connectionString='metadata=res://*/Models.PizzaByMeModel.csdl|
res://*/Models.PizzaByMeModel.ssdl|
res://*/Models.PizzaByMeModel.msl;
provider=System.Data.SqlClient;
provider connection string="data source=(local);
initial catalog=PizzaByMe;
integrated security=True;
pooling=False;
multipleactiveresultsets=True;
App=EntityFramework;"'
providerName="System.Data.EntityClient" />
When I fire up the website I get:
A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (provider: SQL
Network Interfaces, error: 26 - Error Locating Server/Instance
Specified)
The strange part is that if I remove the connection string - I still get the exact same error. I guess that the EF just can't find the Connection String even when it's there.
Any ideas?
Thanks!
EDIT:
My DBContext is as follows:
public partial class PizzaByMeEntities : DbContext
{
public PizzaByMeEntities()
: base("name=PizzaByMeEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
throw new UnintentionalCodeFirstException();
}
public DbSet<X> Xs{ get; set; }
public DbSet<Y> Ys{ get; set; }
public DbSet<Z> Zs{ get; set; }
}
EDIT 2:
the working connection string is this:
<add name="PizzaByMe" connectionString="Data Source=(local);initial catalog=PizzaByMe;integrated security=True;pooling=False;multipleactiveresultsets=True;" providerName="System.Data.EntityClient" />
Though to make it work - I just used direct ADO.NET connection.
Your derived DbContext class must have the same name as your connection string if you have only implemented a default constructor (or no constructor at all)
public PizzaByMeEntities : DbContext
{
public PizzaByMeEntities()
{
// ...
}
}
If your context has another name then you must specify the name of the connection string in the constructor:
public PizzaByMeContext : DbContext
{
public PizzaByMeContext() :
base("name=PizzaByMeEntities")
{
// ...
}
}
Here are details about connections and connection strings with DbContext: http://blogs.msdn.com/b/adonet/archive/2011/01/27/using-dbcontext-in-ef-feature-ctp5-part-2-connections-and-models.aspx
Edit: Another guess
The connection string must be in the web.config of your MVC app, not in an app.config of a class library project where you possibly have your EF model and DbContext. Is it?
Phewwww.... figured it out!!!
The Context object that the controller created (when you use new context) it created the object without the constructor that chooses the connection string. So it tried to use some non-existing connection string.
For conclusion - any object deriving from DBContext should use a constructor that would specify the connection string.
Thanks guys for helping me out :))

Entity Framework Not Creating Database

Been playing around with the Code First feature of Entity Framework 4.1 using an ASP.NET MVC 3 project.
However the database (SQL Server 2008 R2) does not automatically create the table mapping on application startup. Any ideas on how to make it do so?
The project has only one POCO:
namespace RIS.Models
{
public class Person
{
[Key]
public virtual string NRIC { get; protected set; }
public virtual string FirstName { get; protected set; }
public virtual string MiddleName { get; protected set; }
public virtual string LastName { get; protected set; }
}
}
It also has the following database context class:
namespace RIS.Models
{
public class RIS_DB : DbContext
{
public DbSet<Person> People { get; set; }
}
}
I've added a SQL connection string to the global web.config file as follows:
<add name="RIS_DB" connectionString="Data Source=URAHARA-PC;Initial Catalog=RIS_DB;
Integrated Security=SSPI;Pooling=False" providerName="System.Data.SqlClient"/>
There is also an explicit instruction to create the database if it does not exist in the Global.asax.cs file:
protected void Application_Start()
{
Database.SetInitializer(new CreateDatabaseIfNotExists<RIS_DB>());
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
Asked around on the MSDN forums instead, and got a satisfactory answer:
Entity Framework will not create a database until first access. The current code block in Application_Start() only specifies the strategy to use when creating the database during first access.
To trigger creation of the database on startup, an instance of the database context must be created, and context.Database.Initialize(true) must be invoked.
I have the same issue and found a elegant solution: call the SetInitializer in the constructor of your DbContext:
public class MyDbContext : DbContext
{
protected MyDbContext : this("MyConnection")
{
Database.SetInitializer<MyDbContext>(new CreateDatabaseIfNotExists<MyDbContext>());
}
}
My app setting:
<connectionStrings>
<add
name="MyConnection"
connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\MyDB.mdf;Initial Catalog=MyDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
I know this was already answered by mazatsushi in the rightest way.
But just to clarify it to begginers:
Based in mazatsushi's answer what you have to do is to write:
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SorteoContext>());
using (var context = new SorteoContext())
{
context.Database.Initialize(force: true);
}
inside Application_Start() function in Global.asax.cs
and Boom! works!

Resources