Can't Access my EF Model through The MVC Controller - asp.net-mvc

I'm a beginner to asp.net MVC .
I try to use EF code first with MVC (visual studio 2013).so I have
Domain Classes
DataLayer(Context)
MVC app
i have added two references of my domain classes and DataLayer to the MVC App
But when i add the first Controller i can't find any model class !! or db context !! even though i Rebuild My App and adding the exact connection string in web.config
My DBContext:
public class Context : DbContext
{
public Context()
{
}
public DbSet<Alias> Aliases { get; set; }
public DbSet<Tweet> Tweets { get; set; }
//.........................
}

This happened to me before, try closing your solution and re-opening it. Run clean solution then run build solution. Then try to add the controller again. It worked for me.

It's easy-peasy.
Just right-click, add class (if you don't see ADO.NET Entity Model as an entry, this is the way to find it) then add the entry ADO.NET Entity Model. Then, once you regen your edmx, simply add as a new Web API (or MVC) controller, (I did Web API because that is what I was working on) and make sure to select the Entity Framework version of the controller.
It will ask you for your model. Select the model name of the EDMX you just generated. It should populate the rest. Bam. You're done.

Try to add New Controller like this.
Right click on Controllers folder. Select Add.
Select Controller.
Select MVC 5 Controller with view, using Entity Framework.
OR
Right click on Controllers folder. Select Add.
Select New Scaffolded Item.
Select MVC 5 Controller with view, usingEntity Framework.

Related

Can't create MVC4 controller for classes with a base class (Generated from Entity Framework)

I am using Entity Framework 5 with MVC4 to create a small test-app using Model First.
I have two projects, a data project, and a ui project which references data.
I have my model MYModel.edmx in data which has the following entity's
[ITEM]
[BOOK][DVD]
Where "book" and "dvd" have a base type of the abstract class "Item".
Using the code-generation, it creates the classes for these 3 tables and my dbContext as so:
public DbSet<Item> Items {get;set;}
Not creating any DbSet for accessing "Books" or "DVDs".
IF I try to create a new controller using my data context and a model class of "Books" I get the following error
mynamespace.data.books is not part of the specified mynamespace.data.dbcontext class, and the mynamespace.data.dbcontext class could not be modified to add a dbset<mynamespace.data.books> property to it. (For example )
What is the correct way to go about using EF with base types and model first as I am clearly doing something wrong, should I even be using Model first? Would it be easier to use Code first for this scenario and create the DBContext myself?
I'm not terribly familiar with model-first, but try adding this in your mynamespace.data namespace:
public class DVD : Item{
//Put your DVD specific properties here
}
public class Book : Item{
//Put your Book specific properties here
}
Don't add primary keys here, they will both inherit the ItemId primary key, because in the database both DVD and Book are being stored in the Item table.
Then, add the two models to your context:
public DbSet<DVD> DVDs {get;set;}
public DbSet<Book> Books {get;set;}
A good reference to implementing Table-Per-Hierarchy via code-first can be found here, I'm sorry i don't know of any model-first reference: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application
I had a same problem, but I don't know what causes it. All you need to do is:
Compile the project
Right click your Controllers folder to add your controller
In Data Context class, Add Controller dialog box, manually type your context, and click Add
Hope it help

Questions about model first MVC 3 using Entity Framework

I was playing around with Entity based on this article in Visula Studio Express 2012: http://msdn.microsoft.com/en-us/data/gg685494.aspx
Had to completely re do this after some findings:
According to the article you can create database, this is correct but classes are not created unless you right click on an empty part in the diagram choose properties and select something for "code generating strategies" (I only had default). After that my project didn't build anymore because of errors. Trying to do it again an a newly created project didn't crate the model classes anymore (not sure what I did to make it work the first time).
After creating products in the diagram, create a database and then use that database in a second project to create models the products.cs file is created but without annotations (I had product name as 200 char max but it's not in the products.cs file).
After scaffolding controllers and views in the second project (making models from database created from models in the first project) the product name is incorrectly validated to 200 char max. Even though the designer shows 200 max the products.cs file is missing annotation.
If I am doing something wrong here could anyone explain to me how to create product.cs file from an Entity diagram and still be left with a buildable project?
Is it normal for model classes created from database to have no annotation (for example max 200 char field)?
I like Entity and the idea of it. Lots of documentation out there with videos but for now I'll go out and buy a hat because will pull all my hair out trying to get used to way it works :-)
It's cool to create database with entity classes using the designer but creating the classes from the designer or from the database is not (yet) working properly.
No annotations so no checks for null or anything. I manually created the classes and added annotation for product name:
public int Id { get; set; }
[DisplayName("Product name"),
Required(ErrorMessage = "Product Name is required"),
StringLength(10)]
public string Name { get; set; }
Then right click controllers folder in solution explorer and choose => add => controller => using entity framework as a template to create crud views.
For some reason here I have to create a data context class that creates yet another connection string and database.mdf file but ... form validation works perfectly in JavaScript and on server.

Error:'Unsupported context type' while creating a new controller

I am going to implement MvcMusicStore using ASP.NET MVC3, Linq to Sql class instead of Entity Framework, MS SQL Server 2008 pro instead of express ed.
I got the tutorial from mvcmusicstore.codeplex.com
I used Linq to Sql class and the Datacontext is MvcMusicSrotedataContext. When i try to create a new class using this
it shows an error in a new window when i click add button Error:'Unsupported context Type'
So, could you please help me to solve this?
Thank You.
The built-in MVC scaffolding doesn't support Linq to SQL -- you'll have to use Entity Framework instead. (Or don't use the scaffolding, build your own controller/action logic manually. Or use a scaffolding plugin that supports Linq to SQL.)
I got the same issue with EF. I am using the VS 2012.
Background:
The reason for my case was.. this auto generation process (Scaffolding) seems not recognize the partial class concept.
I used the model first approach and I have used inheritance with the entities.
Ex: entity “B” and “C” is inherited from “A”
So in my generated model class “DataModelContainer” which is inherited from “DbContext”,
There is no definition for “DbSet” and “DbSet”
i.e: the following two lines were not there
public DbSet<B> B { get; set; }
public DbSet<C> C { get; set; }
Generated “DataModelContainer” class I a partial class, so I completed the other part, using the concept of partial class. And this would be a problem for Scaffolding.
Solution
My workaround was, just removed the partial class I added manually. And added the definitions for “DbSet” and “DbSet” in to the auto generated class.
The problem with this solution is, I have to repeat the same thing when I regenerate the model classes.

Entity Framework is trying to create a database, but its not what I want

I have a small asp.net mvc4 application (working fine in my local machine), that uses entity framework v4.1.0.0 with ADO.net DbContext Generator.(SQL Server 2008 r2)
I am adding newer versions of dlls required through the "Add Deployable Dependencies..." context menu in Visual Studio 2010.
I have a shared hosting with godaddy.com, I have uploaded the files to server and created the database, now here comes the problem.When I try to browse my site I get the following error:
CREATE DATABASE permission denied in database 'master'.
I looked this up around and found out that this error was caused by EF code first trying to create database.but i do not want EF code first to recreate the database, how do i turn off this automatic database creation altogether? I have no intentions of using the code-first feature whatsoever.
Please help.
put this code into the Application_Start() method of Global.asax or constructor on your DbContext class
Database.SetInitializer<MyContext>(null);
If you want to recreate database when POCO domains are changed, use following code instead of above
Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());
If you are using EF Migrations, this is what you set for it:
public sealed class DbConfiguration : DbMigrationsConfiguration<DatabaseContext>
{
public DbConfiguration()
{
AutomaticMigrationsEnabled = false;
}
}
But this doesn't answer the question on EF Code First itself. If the database already exists, then EF will not try to create it. So you just need to point it to an existing database. And to make sure the connection string name is the same as the name of the database context. If it is not, you need to provide it to it with some overrides:
public class DatabaseContext : DbContext
{
public DatabaseContext()
: base(ApplicationParameters.ConnectionStringName)
{
}
public DatabaseContext(string connectionStringName)
: base(connectionStringName)
{
}
}

Should I use entity-framework classes or model classes in the Controllers?

I am new to entity framework and mvc.
I am trying to understand what a Controller should pass to the view.
Should it be the class from Models (MySolution.Models.Story) or the class from the entity framework (MySolution.Story).
The problem is that if I pick the one from entity framework, then the DataTypes and html-helpers are not working correctly. If I pick the class from models, then I can't convert from the entity class to the model class, for example:
TrendEntities TrendDB = new TrendEntities();
public ActionResult Details(int id) {
var Country = TrendDB.Countries.FirstOrDefault(c => c.CountryId ==id);
return View(Country);
}
Just use the adp.net entity framework POCO templates to generate. download the template. right click in the entity designer and select "add code generation item" and choose the poco template. Now your objects dont have all of the 'entity framework baggage' with them. Proxies are automatically created behind the scenes and you don't need to do any object mapping.
You can find this template by adding a new item to visual studio 2010, and searching the online templates from within the add dialog for POCO. The template name is:
ADO.NET C# POCO Entity Generator
You are looking for either AutoMapper or ValueInjecter. These two libraries are "Object to Object" mappers, which are designed for mapping values from one object to another object. I have only used AutoMapper before. It is great and pretty easy to pick up. I've heard good things about ValueInjecter as well.
After some investigation, I figured out that I had a design problem.
Long story short, REMEMBER that in MVC 3 we need a to define the following class in the model
public class StoryDBContext : DbContext
{
public DbSet<Story> Stories {get; set;}
}
And then in the controller THAT's the one to use when accessing the Entity Framework.
In the previous version we were not defining the above class and were using the TrendEntities class (that was created by the framework) to access the DB.
That's a bit confusing...
So, in my example, TrendDB should be of type StoryDBContext instead of TrendEntities and things are working as expected.
Use a ViewModel. This is a class that you declare having the properties you want to display on your View.
For example:
var country = TrendDB.Countries.FirstOrDefault(c => c.CountryId == id);
CountryDetails details = new CountryDetails();
details.FirstValueToShow = country.Name;
return View(details);
Remember to strongly type your Details view to the ViewModel.

Resources