Questions about model first MVC 3 using Entity Framework - asp.net-mvc

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.

Related

Can't Access my EF Model through The MVC Controller

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.

MVC3 Validation with Entity Framework Model/Database First

I want to use MVC 3 and the Entity Framework for my application.
The model will be stored in a different assembly to the MVC app.
The choice I'm making is either to use the EF to generate my entities or to use code first.
With code first, I can decorate members with [Required] etc... But how would I go about adding those attributes if EF has generated entities from the DB?
Having EF generate my entities will save a lot of time, but I want MVC to auto populate the validation depending on how I've decorated my members. Does this make sense? If so, how would I do that?
In that case, MetadataTypeAttribute is used. You can combine it with partial classes to achieve desired results
And by the way, in your place i would do more research when deciding between using Database First and Code First designs. That all is not about saving time when generating entities, there's much more difference between those two approaches. For the time saving purpose, you can use EF Power Tools to generate code first entities from database - simple.
Better than auto generating your entities, I recommend you to use Code First or mapping an existing database to POCO's classes (not generating the entities, just creating them by hand and mapping them to the existing database)
Scottgu wrote about using EF "Code First" with an existing database.
Check this out:
In your model template (file with extension model.tt) you can hack this template for generating decorators, in this example I add the [Required] decorator plus an error message
var simpleProperties = typeMapper.GetSimpleProperties(entity);
if (simpleProperties.Any())
{
foreach (var edmProperty in simpleProperties)
{
if(!edmProperty.Nullable)
{#>
[Required(ErrorMessage="<#=String.Format("The field {0} is required",edmProperty.ToString())#>")]<#
}#>
<#=codeStringGenerator.Property(edmProperty)#><#
}
}
So the result is something like this
[Required(ErrorMessage="The field Id is required")]
public long Id { get; set; }
PS: You can also add the
using System.ComponentModel.DataAnnotations; by editing the template.
Hope this can help you up.

by default where the data is stored in mvc 3

simply i take mvc 3 project then add model "class1" in that there is another class "person"
in class1 there is two properties id,name and
in class person i inherits dbcontext class and it contains
"public DbSet classes { get; set; }"
and i take default1controller with read/write actions and views, using entity framework and
set
model class "class1" and
data context class "person"
so now my program runs successfully
and i can insert the data but i don't know that where it stores the data.
plz help me.
It might use SQL Server Compact which stores data in a file inside the ~/App_Data folder.
I've not yet used MVC 3 but have a look at your Visual Studio solution. See if there is an App_data folder and expand that. In there you might see an MDF database. Chances are the data is stored in there.
The only thing that I would add to #ManishG's comment:
it stores the data in my local sqlexpress
is that, for connecting to a sqlexpress instance, you should put (local)\SQLEXPRESS in the Server Name field if you are creating a connection from VS 2010 Server Explorer.

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.

How to create a MVC 2 DisplayTemplate for a field whose display format is dependent on another field?

If I have a property whose display format is dependent on the value of another property in the view model how do I create a display template for it?
The combination of field1's display being dependent on field2's value will be used throughout the app and I would like to encapsulate this in a MVC 2 display template.
To be more specific, I've already create a display template (Social.ascx) for custom data type Social that masks a social security number for display. For instance, XXX-XX-1234.
[DataType("Social")]
public string SocialSecurityNumber { get; set; }
All employees also have an employeeID. Certain companies use the employee's social security number as either the whole employee id or as part of it. I need to also mask the employeeID if it contains the social. I'd like to create another display template (EmpID.ascx) to perform this task.
[DataType("EmpID")]
public string EmployeeID { get; set; }
The problem is that I don't know how to get both properties in the "EmpID" template to be able to perform the comparison.
Thanks for the help.
This might not directly answer your question but I'm wondering why the Employee ID is only sometimes marked out. I know there are legal requirements to doing so for the social but the employee ID is (or should be) somewhat sensitive as well. I would think it would be better to default to marking out both unless the logged in user had whatever privileges made them fully readable.
If you can do this that would probably simplify your logic/design somewhat.
Cant you create a custom ViewModel class containg both SocialSecurityNumber and EmployeeID and create a custom editor template for that class?

Resources