ASP MVC 5 partial, class parameter issue - asp.net-mvc-5

I am learning and I am trying to change the parameter name of my autogenerated partial class using [Display()] attribute but I am getting this error message.
Severity Code Description Project File Line Suppression State Error CS0246 The type or namespace name 'Student_Age' could not be found (are you missing a using directive or an assembly reference?) EFScuffolding C:\Users\kusha\source\repos\EFModel\EFScuffolding\Models\Students.cs 20 Active
This is my autogenerated code for Student Class
namespace EFDemo.Models
{
using System;
using System.Collections.Generic;
public partial class Student
{
public int StudentID { get; set; }
public string Student_Name { get; set; }
public string Student_Major { get; set; }
public Nullable<int> Student_Age { get; set; }
}
}
This the class I am using to modify the parameters for display
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using EFScuffolding.Models;
namespace EFDemo.Models
{
[MetadataType(typeof(StudentMetaData))]
public partial class Student
{
}
public class StudentMetaData
{
[Required]
public int StudentID { get; set; }
[Required]
[Display(Student_Age = "Student Name")]
public string Student_Name { get; set; }
[Required]`enter code here`
[Display(Student_Major = "Student Major")]
public string Student_Major { get; set; }
[Required]
[Display(Student_Age = "Student Age")]
public Nullable<int> Student_Age { get; set; }
}
}
I am using MVC 5 ,EF6 and Visual Studio 17. Am I missing anything in the code.

Your not using the DisplayAttribute correctly. You need to set its Name property to the text you want to display
[Display(Name = "Student Name")] // not Student_Age = "Student Name"
public string Student_Name { get; set; }
and ditto for the other 2 properties
However, in asp.net-mvc, use view models, not partial classes. Refer What is ViewModel in MVC?

Related

Object reference not set to an instance of an object in Entity Framework

I got question on this error which I cannot solve. I am using Entity Framework database first. And before that I have deleted the entity model and create a new one. I am not sure it will affect or not.
This is my viewModel
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
namespace MVCTutorial.Models
{
public class OtherIncViewModel
{
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<UserGroup> UserGroups { get; set; }
public virtual DbSet<Patient> Patients { get; set; }
//User
public int UserId { get; set; }
public string UserFullName { get; set; }
public string UserIC { get; set; }
[DataType(DataType.Password)]
[Required(ErrorMessage = "This field is requiered.")]
public string UserPassword { get; set; }
public string UserEmail { get; set; }
public Nullable<int> UserGroupId { get; set; }
public string UserMMCRegistrationNo { get; set; }
[DisplayName("UserName")]
[Required(ErrorMessage = "This field is requiered.")]
public string UserLogin { get; set; }
public string UserFaxNo { get; set; }
public string UserDesignation { get; set; }
public string UserStatus { get; set; }
public string UserContact { get; set; }
public virtual UserGroup UserGroup { get; set; }
public string LoginErrorMessage { get; set; }
//Patient
public int PatientId { get; set; }
public string PatientName { get; set; }
public string PatientIC { get; set; }
public int PatientAge { get; set; }
public string PatientGender { get; set; }
public string Hospital { get; set; }
public string Ward { get; set; }
public string Department { get; set; }
public string Barcode { get; set; }
public string Race { get; set; }
public string PatientErrorMessage { get; set; }
public virtual ICollection<CaseOtherInc> CaseOtherIncs { get; set; }
public virtual ICollection<DraftCaseOtherInc> DraftCaseOtherIncs { get; set; }
}
}
This is my controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVCTutorial.Models;
namespace MVCTutorial.Controllers
{
public class WardStaffController : Controller
{
OtherIncContext db = new OtherIncContext();
// GET: WardStaff
public ActionResult Index() //Ward Staff Inbox
{
return View();
}
public ActionResult CreateTransfusion() //Ward Staff Create Transfusion
{
return View();
}
public ActionResult CreateIBCT() //Ward Staff Create IBCT
{
return View();
}
public ActionResult CreateNearMiss() //Ward Staff Create Near Miss
{
return View();
}
[HttpPost]
public ActionResult SearchPatient(MVCTutorial.Models.OtherIncViewModel patient)
{
using (OtherIncContext db = new OtherIncContext())
{ //I am wondering here why my local variable does not reference the namespace in this case is MVCTutorial. Is this why i get the null exception? I have check my database...i didn't have null record.
var patientDetails = db.Patients.Where(x => x.PatientIC == patient.PatientIC).FirstOrDefault();
if (patientDetails == null)
{
patient.PatientErrorMessage = "Please enter patient's IC number.";
return View("CreateOtherIncident", patient);
}
else
{
Session["PatientName"] = patientDetails.PatientName;
}
return RedirectToAction("CreateOtherIncident", "WardStaff");
}
}
This is my view
#model MVCTutorial.Models.OtherIncViewModel
#{
ViewBag.Title = "CreateOtherIncident";
Layout = "~/Views/Shared/_LayoutWardStaff.cshtml";
}
<h2>CreateOtherIncident</h2>
<h2>Reported By:</h2>
<p> Name: #Session["UserFullName"].ToString()</p>
<p>Email Address: #Session["UserEmail"].ToString()</p>
<p>Date:</p>
<p>Designation No.: #Session["UserDesignation"].ToString()</p>
<p>Tel.No: #Session["UserContact"].ToString()</p>
<p>Fax.No: #Session["UserFaxNo"].ToString()</p>
<h2>Patient Details:</h2>
#Html.LabelFor(model=>model.PatientIC)
#Html.EditorFor(model=>model.PatientIC)
<p>Patient Name: #Session["PatientName"].ToString()</p> //I get the exception here.
I suspect it is because of the local variable, but I cannot find any further error or exception on that.
Before the exception, To check session should not be null.
like:
#if (HttpContext.Current.Session["PatientName"] != null)
{ //#Session["PatientName"].ToString()
}

Entity Type 'AstNode' has no key defined

I'm porting a data model from EF4 to EF6 Code First. I'm getting the following message when the database creation is attempted. I'm at a loss to understand what is causing this. I don't have any Context, AstNode or JSParser entities. It is also not looking in the Models namespace:
var context = QPDataContext.Create();
var session = context.DataSessions.FirstOrDefault(ds => ds.DataSessionId = sessionId);
Throws this exception:
{"One or more validation errors were detected during model generation:
QPWebRater.DAL.Context: : EntityType 'Context' has no key defined. Define the key for this EntityType.
QPWebRater.DAL.AstNode: : EntityType 'AstNode' has no key defined. Define the key for this EntityType.
QPWebRater.DAL.JSParser: : EntityType 'JSParser' has no key defined. Define the key for this EntityType.
(many more similar errors snipped).
"}
Here is my database context (I've simplified it a bit):
QPWebRater.DAL.QPDataContext.cs:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using Microsoft.Ajax.Utilities;
using QPWebRater.Models;
using QPWebRater.Utilities;
namespace QPWebRater.DAL
{
public class QPDataContext : DbContext
{
public QPDataContext()
: base("DefaultConnection")
{
Database.SetInitializer<QPDataContext>(new CreateDatabaseIfNotExists<QPDataContext>());
}
public static QPDataContext Create()
{
return new QPDataContext();
}
public DbSet<DataSession> DataSession { get; set; }
public DbSet<Document> Documents { get; set; }
public DbSet<Driver> Drivers { get; set; }
public DbSet<Location> Locations { get; set; }
public DbSet<Lookup> Lookups { get; set; }
public DbSet<Quote> Quotes { get; set; }
public DbSet<Vehicle> Vehicles { get; set; }
public DbSet<Violation> Violations { get; set; }
}
}
QPWebRater.Models.DatabaseModels.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace QPWebRater.Models
{
public partial class DataSession
{
public DataSession()
{
this.Vehicles = new HashSet<Vehicle>();
this.Drivers = new HashSet<Driver>();
...
}
public string DataSessionId { get; set; }
public System.DateTime Timestamp { get; set; }
...
}
public partial class Document
{
public int DocumentId { get; set; }
public int QuoteId { get; set; }
public string DocumentType { get; set; }
public string Url { get; set; }
public string Description { get; set; }
public virtual Quote Quote { get; set; }
}
public partial class Driver
{
public Driver()
{
this.Violations = new HashSet<Violation>();
}
public int DriverId { get; set; }
public string DataSessionId { get; set; }
...
}
}
I solved this by examining all of the DbSet definitions. I had pared down the data model while also upgrading it. I had removed the Lookup model class but neglected to also remove the DbSet<Lookup> Lookups { get; set; } property.
This resulted in the class being resolved as Microsoft.Ajax.Utilities.Lookup. At runtime, EntityFramework tried to add a corresponding database table which failed miserably. If you are running into a similar problem then double check the generic types in your DbSet properties.

I need a mix of table per hierarchy or type in entity framework

I have 3 entities and I want to use them for EF as POCO`s:
TimeTable is the base class for Period and LessonPlanner classes.
How can I use/map these 3 classes with EF 5.0 or higher?
I want to get 2 sql tables created: Period and LessonPlanner.
EF supports only Table per hierarchy or Table per type.
Either I get one table containing all properties as fields OR I get 3 separated tables.
I just want 2 tables whatever approach I have to take I do not care: Database/Model/Code first...
public class TimeTable
{
public int Id { get; set; }
public int LessonNumber { get; set; }
public string SchoolclassNumberForSunday { get; set; }
public string SchoolclassNumberForMonday { get; set; }
public string SchoolclassNumberForTuesday { get; set; }
public string SchoolclassNumberForWednesday { get; set; }
public string SchoolclassNumberForThursday { get; set; }
public string SchoolclassNumberForFriday { get; set; }
public string SchoolclassNumberForSaturday { get; set; }
}
public class Period : TimeTable
{
public enum WeekType
{
A,
AB,
}
}
public class LessonPlanner : TimeTable
{
public DateTime LessonDate { get; set; }
}
Using code first in Entity Framework 5, in the DbContext derived class, override OnModelCreating and add the following code. I've not tried it with your types but I've used a variant of this to create two classes for a three deep hierarchy.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Period>()
.Map<Period>(p => p.MapInheritedProperties())
.ToTable("Period");
modelBuilder.Entity<LessonPlanner>()
.Map<LessonPlanner>(lp => lp.MapInheritedProperties())
.ToTable("LessonPlanner");
}

Console App Interface from another DLL Implementation Error

I have an interface in a DLL and am implementing it in a Console App for Testing
My Interface is as Follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Gemini.Data.Interfaces
{
public interface IUser
{
IEnumerable<IUserDetails> UserProfiles { get; set; }
string AdUserName { get; set; }
}
public interface IUserDetails
{
int UserId { get; set; }
string DisplayUserName { get; set; }
string OfficeCode { get; set; }
string UserEmail { get; set; }
string AdLogin { get; set; }
bool? LastActiveUser { get; set; }
Gemini.Data.App_Consts.Access_Rights UserAccess { get; set; }
bool IsPM { get; set; }
bool IsSPM { get; set; }
bool IsVdbUser { get; set; }
DateTime? LastModified { get; set; }
DateTime? LastLoginUse { get; set; }
int? LastModifiedBy { get; set; }
}
}
and when I try to use it in the Testing App I get the following
The type or namespace name 'IUser' does not exist in the namespace 'Gemini.Data.Interfaces' (are you missing an assembly reference?)
the Console App is as Follows
using System;
using System.Collections.Generic;
using Gemini.Data.Interfaces;
namespace ConsoleApplication2
{
public class User : Gemini.Data.Interfaces.IUser
{
private IEnumerable<IUserDetails> _UserProfiles = null;
#region IUser Members
public IEnumerable<IUserDetails> UserProfiles
{
get { return _UserProfiles; }
set { _UserProfiles = value; }
}
public string AdUserName { get; set; }
#endregion
}
class Program
{
static void Main(string[] args)
{
User u = new User();
Gemini.Data.Main.UserDetails ud = new Gemini.Data.Main.UserDetails(u, "Qpirate");
}
}
}
Visual Studio seems to reference the Interfaces and I can call Go To Definition on the Classes.
Anyone know of something else I can try?
I have already checked that the console app its targeting the same .NET Framework as the DLL.
The same issue happened to me once, and i found out that the assembly name, and console app name were same in my case.
To troubleshoot, i would suggest first make sure that assembly name are different for dll, and console app.
If that does not solve, try specifying different namespaces (both default namespace in project tab, and rename existing namespaces).
If that also does not solve, try to first merger the code of dll into app, and then move one by one. I hope codebase is small in your case.
I eventually just deleted the old Solution and started again, but one thing i did notice was that when i created a console app the Target Framework was ".NET Framework Client Profile"

AutoMapper - How to map a concrete domain class to an inherited destination DTO class?

I have a flat domain class like this:
public class ProductDomain
{
public int ID { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string Description { get; set; }
public string Price { get; set; }
}
I have two DTO classes like this:
public class ProductInfoDTO
{
public int ID { get; set; }
public string Manufacturer { get; set; }
public string Model{ get; set; }
}
public class ProductDTO : ProductInfoDTO
{
public string Description { get; set; }
public string Price { get; set; }
}
Now the problem is:
Scenario #1:
Mapper.CreateMap<ProductDomain, ProductInfoDTO>() // this mapping works fine
Scenario #2:
Mapper.CreateMap<ProductDomain, ProductDTO>() // this mapping is not working and throws System.TypeInitializationException
So my question is how to create mapping between ProductDomain and ProductDTO (which inherits ProductInfoDTO) without breaking the definition of both source and destination classes. Also I dont want to introduce any new inheritance for the domain class ProductDomain.
Thanks
You can build your own custom TypeConverter like this
public class ProductDomainToProductDTOConverter : ITypeConverter<ProductDomain, ProductDTO>
{
public ProductDTO Convert(ProductDomain source)
{
ProductDTO product = new ProductDTO();
product.Price = source.Price;
...
return product;
}
}
And then create a map with your custom TypeConverter like this
Mapper.CreateMap<ProductDomain, ProductDTO>().ConvertUsing<ProductDomainToProductDTOConverter>();

Resources