creating controller doesn't work - asp.net-mvc

I'm learning asp.net mvc3 from w3schools and following that tutorial.http://w3schools.com/aspnet/mvc_models.asp In the section "ASP.NET MVC Models" I have created the model like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MvcDemo.Models
{
public class MovieDB
{
public int ID { get; set; }
public string Title { get; set; }
public string Director { get; set; }
public DateTime Date { get; set; }
}
public class MovieDBContext : DbContext
{
public DbSet<MovieDB> Movies { get; set; }
}
}
Then I was going to add a controller according to the instructions.
In the Solution Explorer, right-click the Controllers folder, and select Add and Controller
Set controller name to MoviesController
Select template: Controller with read/write actions and views, using Entity Framework
Select model class: MovieDB (McvDemo.Models)
Select data context class: MovieDBContext (McvDemo.Models)*
Select views Razor (CSHTML)
Click Add
But the problem I have is that the drop down list doesn't show MovieDB (McvDemo.Models) in Model Class and Data Context Class to be selected. Can anyone please help me? Thanks.

You should just be able to recompile (Shift-Ctrl-B) and then try it again - it will be there. Otherwise you can always just declare it yourself at the top of a blank view, but that will not provide the scaffolding that the generator does:
#model MvcDemo.Models.MovieDB;

I recompiled but that did not fix the issue for me and yes I am doing the same thing and ran into the same exact issue. The problem for me was caused by visual web developer not being able to connect to my Movies database. I had to change the definition of my connectionString within web.config like this:
<add name="MovieDBContext"connectionString="Data Source=c:\sites\w3schools_demo\MvcDemo2\MvcDemo2\App_Data\Movies.sdf" providerName="System.Data.SqlServerCe.4.0"/>
If you are having this issue you will need to change the "Data Source" path to point to your Movies.sdf database file.

Related

Entity Framework creates an empty migration file

I created my initial project in Visual Studio and discovered I had used SQL Server after I created my initial migration. I then changed all the connection information to use MYSQL and connected successfully. I created the initial migration again and it created all the ASP security tables. I added a new model and updated the database, but it created an empty migration (just UP/DOWN methods)
I've tried multiple fixes I found here and other sites. I backed out the second migration and retried. I tried forcing the migration again (-f). I dropped the new MYSQL db and deleted the migrations then started over, all with the same result.
Here is my model code:
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace congresssucks_conversion.Models
{
public class BlogPost : DBContext
{
public int Id { get; set; }
public string Title { get; set; }
public string ShortPost { get; set; }
public string Post { get; set; }
public string Tags { get; set; }
public DateTime Updated { get; set; }
}
}
And here is the migration file:
namespace congresssucks_conversion.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class blogpost : DbMigration
{
public override void Up()
{
}
public override void Down()
{
}
}
}
It completes successfully and no errors in the Terminal Window.
You're combining two separate things, your model class and your database context.
Your BlogPostm class shouldn't inherit DbContext, it should be just a plain C# class.
Then you make a new class that looks something like this:
public class BlogDbContext : DbContext
{
public DbSet<BlogPostm> Posts { get; set; }
}
Now you have a class that can represent a single post, and another class that can represent a database with a table of multiple blog posts. The migration generator is looking for those DbSet<whatever> properties, so you should see real migrations after this change.
There are a lot more ways you can describe what you want Entity Framework to do with your database, so it would be worth reviewing an Entity Framework tutorial.
Try to delete a record of last migration from _MigrationHistory table. Maybe This record had been incorrectly created before added DbSet for the new model object to DbContext class. After this delete, new migration was created with correct Up() and Down() methods.

How Entity Framework know to which class is take to add migration?

My question is very simple, I am using Entity Framework with asp.net MVC.
I am not sure this question is helpful or not, but I have a doubt.
How entity framework should known, that he has to add migration for which class, why EF will not generate migration for ViewModel class ?
I am just want to know how EF will differentiated between ViewModel.cs class and Model.cs class and add migration only for model.
Thanks in advance.
I think it checks which classes have been added to a DbContext.
using System.Data.Entity;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity.Infrastructure;
namespace MigrationsDemo
{
public class BlogContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
}
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
}
}
Blog will now be considered with the migration. Please see this link for more information on code-first migrations: https://msdn.microsoft.com/en-us/data/jj591621.aspx
There are some places that you can add configuration to Entity Framework, but in its basic form, it iterates the properties on your DbContext class (with a public get), and considers all properties of type IDbSet to be a part of the data model.
The properties do not have to have a set. For example, this is a valid entity definition in DbContext that EF will pick up and generate Migration for:
public IDbSet<MyEntity> MyEntities
{
get { return Set<MyEntity>(); }
}

How to show master-detail data on an ASP.NET mvc page?

I've already read several SO questions about this topic, but honestly most of them have been way too complex for me. I'm very new to ASP.NET mvc.
I have a sample ASP.NET mvc 4 app that I created by following along with (and deviating just a bit from) the Movie database tutorial. It has the built-in account bits, the Entity Framework (which has turned out to be a pain any time I change anything) plus 2 models that I built myself based on the models from the tutorial:
1) Bug
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace MasterDetailPractice.Models
{
public class Bug
{
public int BugID { get; set; }
public string BugTitle { get; set; }
public DateTime BugDate { get; set; }
public string BugStatus { get; set; }
[Column(TypeName = "ntext")]
[MaxLength]
public string BugDescription { get; set; }
}
public class BugDBContext : DbContext
{
public DbSet<Bug> Bugs { get; set; }
public DbSet<Comment> Comments { get; set; }
}
}
2) Comment
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
namespace MasterDetailPractice.Models
{
public class Comment
{
public int CommentID { get; set; }
public int BugID { get; set; }
public int UserID { get; set; }
public DateTime CommentDate { get; set; }
[Column(TypeName = "ntext")]
[MaxLength]
public string CommentText { get; set; }
}
}
When I run my app I'm able to go to /Project and get the standard Index view with the Add link, where I can add a Bug. Once added, I see the usual Edit/Details/Delete links.
When I run my app I'm also able to go to /Comment and get the standard Index view with the Add link, where I can add a Comment. Once added, I see the usual Edit/Details/Delete links.
Up to this point, I'm OK. The CRUD forms work, they just don't work together.
THE PROBLEM:
Currently, in order to make a Comment apply to a Bug, I have to actually input a BugID into the /Comment/Create form. And then the Comments are all only available at the /Comment/ route.
Instead, I need the following to happen:
The "Add Comment" form should automatically know what BugID to
save without a user having to input it.
A master-detail presentation of the data: The /Comment/Index view should appear at the bottom of the /Bug/Edit and/or Bug/Details page and show only the Comments related to the current Bug.
The "Add Comment" link should only appear from the /Bug/Edit or
/Bug/Details page, so Comments are never added without relating to a Bug.
It's kind of amazing that I haven't been able to figure this out myself, after spending 3 days poring over every Google result and SO post I can find on the topic. That said, here I am, hoping to learn the simplest possible implementation of this.
Do I need to post more code (the Controllers, for example, or the Views) in order for this question to be properly answerable?
Looking forward to getting the slow-learning train to start pulling out of the station...
Okay you need to do a few things.
First, create a new action method in your CommentController that looks like this.
public ActionResult Index(int bugId)
{
// Your logic to fetch all comments by BugID through EntityFramework or whatever
return View(data);
}
Now, in your Bug/Edit.cshtml or Bug/Details.cshtml pages add the following line to render those actions inline.
#Html.RenderAction("Index", "Comment", new { #bugId = Model.BugID }
In this case, you should be returning a BugModel back to your Bug/Edit.cshtml or Bug/Details.cshtml anyway as your model.
This should show you the form you need, with the BugID from the model being passed through.
For your last question, just put the "Add Comment" link within your Comment/Index.cshtml view since it will only appear anyway within the context of a bug. You will probably need to wrap this around a form that posts to your CommentController.
Here's a helpful link on working with forms in ASP.NET 4.
http://www.asp.net/mvc/tutorials/hands-on-labs/aspnet-mvc-4-helpers,-forms-and-validation

How do I use my own Model classes in conjunction with EF entity classes in MVC?

So I am new to MVC and am working now with MVC3 and the Entity Framework. I am currently using a Model/Schema 1st approach as the database already exists. Therefore I create my ADO.NET Entity Data Model (.edmx) and I have all the needed entities in my MVC app. So far so good on all this.
However let's say one of my Entities is a 'Customer' entity. I can see the auto-generated partial class inheriting from EntityObject in MyEntites.Designer.cs. At this point I want to add some custom business logic to my MVC Model. Natuarally I believe the answer is to use my own partial class created in the Model named 'Customer' as well.
I did a lot of searching on this before asking the question and see all kinds of information on POCO, T4 templates, modifying auto-generated code, etc and am lost. Is it a royal pain to add my own business logic and custom code to the auto-generated entities from EF? I certainly don't want to modify the auto generated code over and over.
I need a straight forward explanation to make the proverbial 'light bulb' go on, and then I can take-off from there. Can someone help me answer how to do this please?
Thanks!
Keep your own class code in a different file, but use the same class and namespace. This will help avoid your code being overwritten by the T4 code generator.
Extending Entity Framework Generated Types
You can also add attributes to generated classes by using a meta class:
Adding Attributes to Generated Classes
Those codes are auto-generated and will be over written on each model update or change.
You can achieve what you need through extending models. Suppose that EF generated the following entity class for you:
namespace YourSolution
{
using System;
using System.Collections.Generic;
public partial class News
{
public int ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int UserID { get; set; }
public virtual UserProfile User{ get; set; }
}
}
and you want do some work arounds to preserve your you data annotations and attributes. So, follow these steps:
First, add two classes some where (wherever you want, but it's better to be in Models) like the following:
namespace YourSolution
{
[MetadataType(typeof(NewsAttribs))]
public partial class News
{
// leave it empty.
}
public class NewsAttribs
{
// Your attribs will come here.
}
}
then add what properties and attributes you want to the second class - NewsAttribs here. :
public class NewsAttrib
{
[Display(Name = "News title")]
[Required(ErrorMessage = "Please enter the news title.")]
public string Title { get; set; }
// and other properties you want...
}
Notes:
1) The namespace of the generated entity class and your classes must be the same - here YourSolution.
2) your first class must be partial and its name must be the same as EF generated class.
Go through this and your attribs never been lost again ...

MVC 2 Data annotations problem

Going mad now. I have a MVC solution that i've upgraded from MVC 1 to 2. It all works fine.... except the Validation!
Here's some code:
In the controller:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using MF.Services.Authentication;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace MF.Controllers
{
//basic viewmodel
public class LogOnViewData
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
[HandleError]
public class AccountController : Controller
{
[HttpPost]
public ActionResult LogOn(LogOnViewData lvd, string returnUrl)
{
if (ModelState.IsValid)
{
//do stuff - IsValid is always true
}
}
}
}
The ModelState is always valid. The model is being populated correctly however. Therefore, if I leave both username and password blank, and post the form the model state is still valid. Argh!
Extra info: using structure map for IoD. Previously, before upgrading to MVC 2 was using the MS data annotation library so had this in my global.asax.cs:
ModelBinders.Binders.DefaultBinder = new Microsoft.Web.Mvc.DataAnnotations.DataAnnotationsModelBinder();
Have removed that now.
I'm sure i'm doing something really basic and wrong. If someone could point it out that would be marvellous.
Cheers
Half way through the development of MVC2, they went from input validation to model validation, which should in all cases validate your object completely. Make sure you're using the latest version (RTM).
However, [Required] merely indicates the attribute must not be null. Unfortunately, String.Empty -which is the default for strings- is not null, so model validation will pass for empty strings.
See this post by Brad Wilson for important details.
As a solution, you could use the [RegularExpression("....")] to impose restrictions on the minimum string length and allowed characters.

Resources