say I have the following code:
Truck truck = new Truck();
truck.id = '12323'
return view(truck);
Note that the Entity Truck has a number of fields associated with
it such as color, Note, etc.
For Note, I like to add an annotation for the maxlength.
How do I go about adding and annotation. I know this is usually done in a class
but in this case, I do not have a class as I am getting Truck directly from entity framework.
You will want to make a partial class (aka buddy class) for your entity class and give it a MetadataType attribute. Check out this example with validation attributes. Specifically the section labeled Using Data Annotation Validators with the Entity Framework.
http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs
Related
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
I need just a few confirmation that I do some stuff in the right way or I make horrible mistake :)
1) I put my data access layer (MyProject.Domain) in sepparate assembly. There I have entity object "User" that has properties in 1:1 relation with "User" table in my database. I also extend this user from "MembershipUser" because I use custom schema for membership. Is this good location to store MembershipUser entity?
2) I have "Image" table in database and "Image" entity in my domain library. Image in database has "AuthorId" column which is FK to "User" table. Also image contain list of "comments". So I structure Image domain object like this:
public class Domain
{
public int ImageId{get;set;}
public string Name{get;set;}
public Author Author{get;set;}
public IEnumerable<Comment> Comments{get;set;}
}
Is this good way or maybe I should assemble all data in a ViewModel class?
You should really make a distinction between domain models and view models. Domain models are those classes that represent your domain business entities. It could be EF autogenerated classes or whatever. So even being aggregate classes they are still domain models as they aggregate domain entities and could be stored alongside with other domain models.
View models are classes that are specifically defined for a given view. The view models are always defined inside the ASP.NET MVC project because they are tightly coupled to specific views which are themselves defined in the ASP.NET MVC project. Domain models could be defined in separate assembly. They are intended to be resused in other applications as well. Think of your domain models as the core of your business. If tomorrow ASP.NET MVC is no longer modern, and something else comes out you should still be able to reuse your domain models. The view models are only a specific representation of your domain models for some given and specific view.
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.
I am pretty new to MVC and I am looking for a way to design my models.
I have the MVC web site project and another class library that takes care of data access and constructing the business objects.
If I have in that assembly a class named Project that is a business object and I need to display all projects in a view ... should I make another model class Project? In this case the classes will be identical.
Do I gain something from doing a new model class?
I don't like having in views references to objects from another dll ... but i don't like duplicating the code neither.
Did you encounter the same problem?
I usually use a combination of existing and custom classes for models, depending on how closely the views map to the actual classes in the datastore. For pure crud pages, using the data class as the model is perfect. In real world use though you usually end up needing a few other bits of data. I find the easiest way to combine them is something like
// the class from the data store
public class MyDataObject {
public string Property1 {get;set;}
public string Property2 {get;set;}
}
// model class in the MVC Models folder
public class MyDataObjectModel {
public MyDataObject MyDataObject {get;set;}
// list of values to populate a dropdown for Property2
public List<string> Property2Values {get;set;}
// related value fetched from a different data store
public string Property3 {get;set;}
}
I also have quite a few model classes that are just a set of form fields - basically corresponding to action parameters from a particular form rather than anything that actually ends up in the database.
If it is exactly the same project then obviously don't need to duplicate the Project class, just use it as is in the view. But in real life often views have specific requirements and it it a good practice to define view model classes in your MVC application. The controller will then map between the model class and the view model to be passed to the view.
You will likely find differing opinions on this. I will give you mine:
I tend to, by default, reuse the object. If the needs of the view change and it no longer needs most/all of the data in the business object, then I'll create a separate view. I would never change the business object to suit the view itself.
If you need most/all of the information in the business object, and need additional data, then I would create a view that holds a reference to the business object and also has properties for the additional data points you need.
One benefit of reusing the business object is that, depending on the data access technology you are using, you can get reuse out of validation. For isntance, ASP.NET MVC 3 coupled with Entity Framework is nice as they both use the attributes in the System.ComponentModel namespace for validation.
That depends on what you mean by model. In the architecture I typically use, I have my Domain model, which is a collection of classes in a separate class library. I use DataAnnotations and built in validation to automatically validate my model when saving.
Then there is the View model, which I place in my MVC project. View models only have the information relevant to the view. I use data annotations here as well since MVC will automatically use them for my validation.
The reason for splitting the model this way is that you don't always use every piece of your domain model in a view. That means you either have to rebuild the data on the backend or you have to stash it in hidden fields. Neither is something I like,.
Is there a way to a coded class called "Pessoa" decorate some atttribute to be referenced with a conceptual class named as "Person" that is in a conceptual model ? I'm mean:
[Table("Person")] // or something like that
public class Pessoa
I tried
[EdmEntityTypeAttribute(Name = "Person")]
but no success....
Here is MS answer:
Currently, Entity Framework doesn't
support custom mapping between Object
and Conceptual types (names should
match). However, we will be
considering this feature for future
releases.
Thanks,
Kavitha Jonnakuti
Entity Framework test team