MVC how to hide an ID field when creating VIEW using Scaffolding - asp.net-mvc

I have a Class generated with POCO T4 Template, I'm using this code to adding to the Partial Class some DataAnnotation.
I would like to know:
How to hide the field OptionId (in the DB is a Primary Key with IDENTITY) so the User does not need input this value in the View (but with setting in the model).
Also I would like to know if [DatabaseGenerated(DatabaseGeneratedOption.Identity)] is REQUIRED or EF with POCO will create automatically the new ID (is IDENTITY)
namespace MyProject.Models
{
[MetadataType(typeof(ReOptionMetadata))]
public partial class ReOption
{
private class ReOptionMetadata
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[HiddenInput(DisplayValue = false)] // Is it correct?
public int OptionId { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Value { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string NoteInternal { get; set; }
}
}
}

#Html.HiddenFieldFor(model => model.ColumnWhichContainsTheId) ?

Related

HowTo fetch data to viewmodel the quickest way

I have a simple problem with my site.
Inside my site, I'm using two different models, with some identical named fields.
Because of collision, I have to give them unique names and for not loosing the modelbinding, I decided to use viewModels.
So I have a Model like this:
namespace MySite.Models
{
public class Function : BaseEntity
{
//Beziehung zur Funktionsgruppe
[Required]
[Display(Name = "Übergeordnete Funktion")]
public int FunctionGroupId { get; set; }
public virtual FunctionGroup FunctionGroup { get; set; }
[Required]
[StringLength(200)]
[Display(Name = "Bezeichnung")]
public string Name { get; set; }
}
}
And I have a new ViewModel like this:
namespace MySite.ViewModels
{
public class FunctionViewModel
{
//Properties of BaseEntity
public int F_Id { get; set; }
[Display(Name = "Erstellt")]
public string F_Created { get; set; }
[Display(Name = "Bearbeitet")]
public string F_LastChange { get; set; }
[Display(Name = "Bearbeiter")]
public string F_ByUser { get; set; }
//Beziehung zur Funktionsgruppe
[Required]
[Display(Name = "Übergeordnete Funktion")]
public int F_FunctionGroupId { get; set; }
public virtual FunctionGroup F_FunctionGroup { get; set; }
[Required]
[StringLength(200)]
[Display(Name = "Bezeichnung")]
public string F_Name { get; set; }
}
}
Now my Question is, is there a way to automatically fetch the data of the corresponding model, while loading the ViewModel?
Something like a kind of function directly inside the { get; set; }?
Actually I load field by field form the model into the ViewModel.
Hope that I could have described Right, what I'd like to do.
Carsten
You can use Automapper for mapping or getting your data from Model to ViewModel or vice-versa. It will be hard for you to map/configure if your name of your property is different so have the same name in view model as well. (If possible)

using entity framework code first in mvc with view model?

so when implementing entity framework code first in mvc, do we separate the view restrictions from view model? this is because for database first the model is generated(so i see the reason to separate it to view model but how about code first?)
The next questions i would ask is it ok to separate view model to another folder? since by default asp.net is MVC there is no view model inside
Model <--- what is this model call? data model? domain model? business model?
public class Student
{
public int ID { get; set; }
[StringLength(250)]
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
}
View Model
public class Student
{
public int ID { get; set; }
[MaxLength(250)]
[Required]
public string LastName { get; set; }
[Required]
public string FirstMidName { get; set; }
[Required]
public DateTime EnrollmentDate { get; set; }
}
Your model that Used in mvc views is viewmodel.
your model that persist in database is domain model.
Your domain model may has some properties that you don't need use it in your client.
Your Service layer must return Dto (data transfer object) to your client and you can map dto to viewmodel .
First Question:
You should use partial class and metadata to seperate , just like below:
[MetadataType(typeof(StudentMD))]
public partial class Student
{
public class StudentMD
{
public int ID { get; set; }
[MaxLength(250)]
[Required]
public string LastName { get; set; }
[Required]
public string FirstMidName { get; set; }
[Required]
public DateTime EnrollmentDate { get; set; }
}
}
Second Question:
It's OK to add a folder name "View Model"
I did it in my project too!

asp.net MVC 4 EntityType: EntitySet has no keys defined

I am a MVC newbie so go easy on me please.
I am getting two errors when I try to add a migration. They are as follows:
EntityType 'Icon' has no key defined. Define the key for this EntityType.
EntityType: EntitySet 'Icons' is based on type 'Icon' that has no keys defined.
I am including the Icon inside another model, like so:
public class Icon
{
public string IconName { get; set; }
public string IconColor { get; set; }
public int BackgroundXPos { get; set; }
public int BackgroundYPos { get; set; }
public string IconColorHover { get; set; }
public int BackgroundHoverXPos { get; set; }
public int BackgroundHoverYPos { get; set; }
}
public class GalleryThumbnail : CSSBoxModel
{
[DisplayName("Thumbnail Image Outline Color")]
public string ThumbnailImageOutlineColor { get; set; }
[DisplayName("Thumbnail Menu Font")]
public CSSFont ThumbnailMenuFont { get; set; }
[DisplayName("Thumbnail Icon Color")]
public Icon ThumbnailIconColor { get; set; }
}
How is this Address class below any different which is working:
public class Address
{
public String Adress1 { get; set; }
public String Adress2 { get; set; }
public String Adress3 { get; set; }
public String City { get; set; }
public String County { get; set; }
public String State { get; set; }
public String Zip { get; set; }
public String Country { get; set; }
}
[Table("UserProfile")] //Could be PP empolyee, Subscriber or Subscriber's customer
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public bool? Gender { get; set; }
public Address Address { get; set; } //billing address
public Address ShipAddress { get; set; }
}
I did not add a key in either my Icon or Address class because I have no intention of storing specific data in my DB. They are merely to be used inside other classes. So wy is one neededing an ID and the other is not?
I have not created public DbSet Icons { get; set; } in my DB Context either.
Also can you tell me what it is called when you use a class inside another ( or instance of class inside a class as in these examples ) ?
Much appreciated!
Since the address entity has no key defined it the Entity Framework assumes it's a complex property, and your UserProfile table will be rendered with columns named Addres_Address1, Address_Address2, Address_Address3, Address_City, and so on...
Even though you haven't declared an EntitySetIcons DbSet on your context class, it's still being added implicitly because one of your other classes somewhere has an ICollection or IEnumerable property defined.
More info on Code Conventions here:
http://msdn.microsoft.com/en-us/data/jj679962.aspx
So, either decorate the collections as NotMapped like #Kamyar said or simply remove the references from any class already declared as a DbSet.
you can use [NotMapped] attribute in System.ComponentModel.DataAnnotations.Schema namespace in EntityFramework.dll:
using System.ComponentModel.DataAnnotations.Schema;
...
[NotMapped]
public Address Address { get; set; } //billing address
[NotMapped]
public Address ShipAddress { get; set; }
Regarding the naming, AFAIK these are called public properties as well.

MVC 4 Entity Framework - Foreign Key to UserProfile

I've created a standard MVC 4 application using the built in account controllers/models/views. I've now tried to add another controller but I want to create a foreign key relationship to an existing user, but im getting the error message:
The ForeignKeyAttribute on property 'CreatedBy' on type 'MVC4App.Models.ListingModel' is not valid. The foreign key name 'UserId' was not found on the dependent type 'MVC4App.Models.ListingModel'. The Name value should be a comma separated list of foreign key property names.
The Listing Model Code is:
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace MVC4App.Models
{
public class ListingModel
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Location { get; set; }
public string Instrument { get; set; }
public string Genres { get; set; }
public string Description { get; set; }
[ForeignKey("UserId")]
public virtual UserProfile CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
}
}
What am I missing here? Or is there a better way I should be doing this?
Also I'm assuming I can just add extra properties to the user profile such as an email address or a link to an avatar image later on in the project?
You have to add the UserId to your entity:
namespace MVC4App.Models
{
public class ListingModel
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Location { get; set; }
public string Instrument { get; set; }
public string Genres { get; set; }
public string Description { get; set; }
public int UserId {get; set;}
[ForeignKey("UserId")]
public virtual UserProfile CreatedBy { get; set; }
public DateTime CreatedOn { get; set; }
}
}

Retrieving [DisplayName] DataAnnotation in T4 template

I have downloaded the MVCScaffolding nuget package within VS2010. I am trying to retrieve a [DisplayName data annotation from my model in order to use it within the index.cs.t4 template.
This page OneToMany Relationships has shown me how to modify the index template in order to provide a link which will take me to the controller index for my child objects. Which in this case from emails to emailrecipients. The problem is i have called my controllers emailcontroller and emailrecipientscontroller rather than their rather less descriptive tables names which i would prefer to hide anyway. i have equally decorated the metadataobject which the t4 template uses(tbl_My_unwieldytablename_emailMetadata) with this displayname (emailrecipients) dataannotation and i was hoping i could modify the template in order to replace the name for the relation to use the displayname which is my controller name i.e.
[MetadataType(typeof(tbl_My_unwieldytablename_emailMetadata))]
public partial class tbl_My_unwieldytablename_email
{
internal sealed class tbl_My_unwieldytablename_emailMetadata
{
[ScaffoldColumn(false)]
[Required(ErrorMessage="id is required")]
public Int32 id { get; set; }
[DataType(DataType.Date)]
public DateTime send_date { get; set; }
[StringLength(255)]
public String title { get; set; }
[DataType(DataType.MultilineText)]
public String message { get; set; }
[StringLength(50)]
public String author { get; set; }
[StringLength(80)]
[DataType(DataType.EmailAddress)]
public String author_email { get; set; }
[DataType(DataType.MultilineText)]
public String attachment { get; set; }
[DataType(DataType.Date)]
public DateTime created_date { get; set; }
public Int32 batches { get; set; }
[DataType(DataType.Date)]
public DateTime complete_date { get; set; }
[DisplayName("emailrecipients")]
public EntityCollection<tbl_My_unwieldytablename_email_recipients> tbl_My_unwieldytablename_email_recipients { get; set; }
}
Cheers
Tim
[Table("tbl_My_unwieldytablename_email")]
Public Class Email
[Table("tbl_My_unwieldytablename_email_recipients")]
Public Class EmailRecipients
Should map your classes to the database tables

Resources