ASP.NET MVC Scaffolding View - Missing Model Property - asp.net-mvc

This is my first time with MVC so please excuse me if I am getting the terminology wrong. I am working on a PluralSight course.
My understanding is scaffolding goes to the model and creates a view when selecting Add View.
Here's my model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace OdeToFood.Models
{
public class RestaurantReview
{
public int Id { get; set; }
public int Rating { get; set; }
public string Body { get; set; }
public string ReviewerName { get; internal set; }
public int RestaurantId { get; set; }
}
}
I go to my controller action and click Add View. My view is missing ReviewerName when it is built. I add ReviewerName manually to my Create view. The ReviewerName appears to not be recognized by the Model Binder when data is added to the database.
I am unsure where to go from here. Thanks for you help!

When you mark the property setter as internal, the scaffolding ignores it. Simply remove that from the property and you should be set (pun intended):
public string ReviewerName { get; set; }

Related

Key data annotation not working when assigned to a separate partial class in my razor web app using efcore .netcore

I am developing an application in razor web apps (asp.netcore) and scaffolding db tables using efcore.
I performed a db-scaffold on my OnlineForms data table, which created my OnlineForms.cs Class. When i directly put the [key] attribute on top of the formid property in this class, I can save to the data table without any issues.
But when I move the [key] data annotation into the partial class OnlineFormsValidation, which references OnlineForms, through the [ModelMetadataType] attribute, and I try to save data; I get the error: "The entity type 'OnlineForm' requires a primary key to be defined."
The Required annotations work properly from inside OnlineFormsValidation class, but the [Key] annotation does not.
Thank you in advance. Any help would be greatly appreciated.
OnlineForm.cs:
namespace VehicleTakeHomeApp.Data.Models
{
public partial class OnlineForm {
[Key] <== works if i put it here, but I want to move it to OnlineFormValidation.cs
public int FormId { get; set; }
public string EmployeeId { get; set; }
public string Name { get; set; }
}
}
OnlineFormValidation.cs:
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
namespace VehicleTakeHomeApp.Data.Models
{
[ModelMetadataType(typeof(OnlineFormValidation))]
public partial class OnlineForm
{
}
public class OnlineFormValidation
{
[Key] <== this annotation is not getting picked up, even though the Required annotations below it get picked up.
public int FormId { get; set; }
[Required(ErrorMessage = "Employee ID is required.")]
public string EmployeeId { get; set; }
[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }
}
}
I had the OnModelCreating method in my dbcontext class commented out. This method contains the HasKey() from the initial db-scaffold.
I uncommented the OnModelCreating method, and now I don't need to add the [Key] annotation, to either class and it works.
It's more of a workaround then a solution, but its works.

Entity Model, grouping models in one model file

I have the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace MyTestWebsite.Models
{
public class Page
{
public int Id { get; set; }
public int AuthorUserId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Content { get; set; }
public bool Hidden { get; set; }
}
public class PageState
{
public int Id { get; set; }
public string Type { get; set; }
}
public class MyTestWebsiteDBContext : DbContext
{
public DbSet<Page> Pages { get; set; }
public DbSet<PageState> PageStates { get; set; }
}
}
I went to create a controller for Page and I found the model structure.. no problems.
This is, I need another model called PageState and my model list does not show this second model.
Is it usual to have a heck load of models.... regardless of them being linked in some way?
Do I just add a model on its own called PageState?
Is it usual to have a heck load of models
Yes, they are called view models. Each view should have a specific view model. It's perfectly normal to have many view models if you have many views. A view model could aggregate one or more of your EF domain models.

MVC 4 Data Annotations

I am using Data Annotations in my MVC 4 project with Scaffolding Nuget to create CRUD views. I am using Layer level Database model not EF.
So my Class look like as below:
[MetadataType(typeof(CustomerMetaData))]
public partial class UserProfile: IBrObject
{
public UserProfile(string aspUserName): this()
{
this.AspUserName = aspUserName;
}
public string AspUserName { get; set; }
public DateTime MetaDateFirstSaved { get; set; }
}
public class CustomerMetaData
{
[ReadOnly(true)]
[ScaffoldColumn(false)]
[DisplayName("ASP UserName")]
public object AspUserName { get; set; }
[DisplayName("Date First Saved")]
[DataType(DataType.Date)]
public object MetaDateFirstSaved { get; set; }
}
when i am trying to create views with Scaffolding Nuget it still shows AspUserName column not hide or not read only.
How i can hide or readonly ?
You use object in metadata and string and DateTime respectively in actual view model so they don't match.
Update
Another possibility (I pretty sure this is what's happening in your case) is because your model type in the view defined as Interface type rather than class type.
In your view replace #model IBrObject with #model UserProfile.
Hope this helps
object AspUserName != string AspUserName

EF Code First Not Generating Tables

I'm working on an EF Code first site, and I've written my classes and a context class, the source of which is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using MySite.SalesTool.Data.Entities;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MySite.SalesTool.Data
{
public class SalesToolEntities : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<Job> Jobs { get; set; }
public DbSet<JobAssigner> JobAssigners { get; set; }
public DbSet<JobFile> JobFiles { get; set; }
public DbSet<JobStatus> JobStatuses { get; set; }
public DbSet<AssignedUser> AssignedUsers { get; set; }
}
}
The project builds fine, but when I go to run the site, no tables are created in the database and I get an error stating that the database can't find whichever context object I try and access, presumably because the code first has not generated any of the necessary tables.
Any ideas why it wouldn't generate any of the tables at all, and not give me any kind of error information?
Do you have an initialization strategy?
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<SalesToolEntities>());
From what you subscribe it sounds like you've created the database yourself. Then you need to specify an initialization
strategy otherwise no tables/data will be added to the database and querying the database will result in an exception: {"The specified table does not exist. [ sometable ]"}

Web forms EF4 CodeFirst CTP5 KeyAttribute not found

I'm using code-first in Web Forms (not MVC) with EF4 and CTP5, and when trying to decorate a property with the [Key] attribute, it doesn't show up in the intellisense and get compilation error saying KeyAttribute was not found. Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
namespace ERP.Models
{
public class CustomerAddress
{
[Key]
public int AddressID { get; set; }
public int CustomerID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public int CityID { get; set; }
public int SateID { get; set; }
}
}
I have included the DataAnnotations library, all looks ok, but the [Key] attribute is not found. Any hint is highly appreciated. Thanks!
I didn't post it as answer first because I wasn't sure if the problem is not elsewhere. You must add System.ComponentModel.DataAnnotations.dll to project references.

Resources