The question I had was how are models supposed to be used? I don't think I am using them correctly. Whenever I make a change to the database (user table, in this case) and rebuild the model, my changes get erased and I end up making the changes again. The changes made are adding attributes and also another column(ConfirmPassword).
Edit: I am using EF 5
This is the model that was created by the database:
using System;
using System.Collections.Generic;
public partial class User
{
public User()
{
this.Documents = new HashSet<Document>();
}
public int UserId { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Grade { get; set; }
}
With my changes:
using System;
using System.Collections.Generic;
using CompareObsolete = System.Web.Mvc.CompareAttribute;
public partial class User
{
public User()
{
this.Documents = new HashSet<Document>();
}
[Key]
public int UserId { get; set; }
[Required]
[StringLength(15, MinimumLength = 3)]
[Display(Name = "Username*: ")]
public string Username { get; set; }
[Required]
[EmailAddress]
[StringLength(25)]
[Display(Name = "Email Address*: ")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(50, MinimumLength = 4)]
[Display(Name = "Password*: ")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm Password*: ")]
[CompareObsolete("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Your Grade*: ")]
public string Grade { get; set; }
}
1. Create UserMetaData Class
public class UserMetaData
{
[Key]
public int UserId { get; set; }
[Required]
[StringLength(15, MinimumLength = 3)]
[Display(Name = "Username*: ")]
public string Username { get; set; }
[Required]
[EmailAddress]
[StringLength(25)]
[Display(Name = "Email Address*: ")]
public string Email { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(50, MinimumLength = 4)]
[Display(Name = "Password*: ")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm Password*: ")]
[CompareObsolete("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Your Grade*: ")]
public string Grade { get; set; }
}
2. Create new partial class in new .cs file and assign metadata class to there by using MetadataType attribute to it.
[MetadataType(typeof(UserMetaData))] // assign type of your metadata here.
public partial class User
{
}
Related
i have 3 models
public class UsersModel
{
[Key]
public int UserId { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 5", MinimumLength = 5)]
public string Name { get; set; }
//20150090
public int? student_ID { get; set; }
[Display(Name = "transcript")]
public string transcript { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "Invalid Name Minimum Length is 2", MinimumLength = 2)]
public string Department { get; set; }
[Required]
[Display(Name = "Phone")]
[DataType(DataType.PhoneNumber,ErrorMessage ="Invalid Phone Number")]
[Range(999999999, 9999999999)]
public int Phone { get; set; }
public int type { get; set; }
}
student
public class StudentsModel
{
[Key]
[Display(Name ="ID")]
public int StudentID { get; set; }
[Required]
public string Name { get; set; }
[Required]//20150090
public string student_ID { get; set; }
[Required]
[Display(Name = "Skills")]
public string Skills { get; set; }
[Required]
[Display(Name = "Gpa")]
[Range(1.00, 4.00, ErrorMessage = "It must be in range 0.00 to 4.00 :)")]
public float Gpa { get; set; }
[Required]
[Display(Name = "Leader")]
public string Leader { get; set; }
[Required]
[Display(Name = "transcript")]
public string transcript { get; set; }
[ForeignKey("UserId")]
public int UserId;
public UsersModel Users { get; set; }
[ForeignKey("IdeaId")]
public int? IdeaId;
public IdeaModel Idea { get; set; }
}
Idea
public class IdeaModel
{
[Required]
[Key]
public int IdeaId { get; set; }
[Required]
public string IdeaName { get; set; }
[Required]
public string IdeaDescription { get; set; }
[Required]
public string tools { get; set; }
public int? SetWith { get; set; }
[Required]
public int Prof1 { get; set; }
public int Prof2 { get; set; }
public int Prof3 { get; set; }
}
when i insert to the database user and student and idea
the foreign key in student model inserted with null value
this is the code for insertion
i want the foreign key in student model to inserted automatically
whit the values of primary key in usernodel and idea model how to make this?
public ActionResult RegisterLeader(regall reg)
{
if (ModelState.IsValid)
{
var user= db.Users.Add(reg.users);
var idea = db.Idea.Add(reg.idea);
var stu = db.Students.Add(reg.students[0]);
db.SaveChanges();
return View("RegisterLeaderPost");
//return Registerfinish();
}
}
this model have the three models
public class regall
{
public List<StudentsModel> students { get; set; }
public UsersModel users { get; set; }
public IdeaModel idea { get; set; }
}
You need to set the Idea property of the student so EF knows to make the relationship.
reg.students[0].Idea = reg.idea;
I had an error in my method when I try to add to the database my interface and it gives me the error,
Argument 1: cannot convert from 'ForumSite.ActionsAndMethods.Registration.IRegistration' to 'ForumSite.Models.User'.
Here is the code in IRegistration:
using ForumSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ForumSite.ActionsAndMethods.Registration
{
public interface IRegistration
{
int UserId { get; }
string Email { get; }
string Password { get; }
string FirstName { get; }
string LastName { get; }
DateTime Birthday { get; }
DateTime DateCreated { get; set; }
string MobileNumber { get; }
string Address { get; }
int UserIsDeleted { get; set; }
int UserRoleId { get; set; }
UserRole UserRole { get; }
}
}
And this is the code in my model:
namespace ForumSite.Models
{
using ActionsAndMethods.Registration;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class User : IRegistration
{
public int UserId { get; set; }
[Display(Name = "Email Address")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#([a-zA-Z]+)\.([a-zA-Z]{2,5})$", ErrorMessage = "Enter Valid Email Address")]
[StringLength(50, MinimumLength = 8, ErrorMessage = "8 to 50 characters only")]
public string Email { get; set; }
[Display(Name = "Password")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^[a-zA-Z0-9]+$", ErrorMessage = "Alphanumeric characters only")]
[StringLength(50, MinimumLength = 8, ErrorMessage = "8 to 50 characters only")]
public string Password { get; set; }
[Display(Name = "Confirm Password")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^[a-zA-Z0-9]+$", ErrorMessage = "Alphanumeric characters only")]
[StringLength(50, MinimumLength = 8, ErrorMessage = "8 to 50 characters only")]
public string PasswordConfirm { get; set; }
[Display(Name = "First Name")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^[a-zA-Z\s]+$", ErrorMessage = "Letters Only.")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^[a-zA-Z\s]+$", ErrorMessage = "Letters Only.")]
public string LastName { get; set; }
[Display(Name = "Birthday")]
[Required(ErrorMessage = "This field required.")]
public DateTime Birthday { get; set; }
public DateTime DateCreated { get; set; }
[Display(Name = "Mobile Number")]
[Required(ErrorMessage = "This field required.")]
[RegularExpression(#"^[0-9]+$", ErrorMessage = "Numeric input only.")]
public string MobileNumber { get; set; }
[Display(Name = "Address")]
[Required(ErrorMessage = "This field required.")]
public string Address { get; set; }
public int UserIsDeleted { get; set; }
public int UserRoleId { get; set; }
public UserRole UserRole { get; set; }
}
}
And lastly, my method which adds the user to my database:
using ForumSite.ActionsAndMethods.Registration;
using ForumSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ForumSite.ActionsAndMethods
{
public class RegisterAction : IRegistration
{
ForumDBEntities ent = new ForumDBEntities();
public void Registration(IRegistration reg)
{
reg.DateCreated = DateTime.Now;
reg.UserRoleId = 1;
reg.UserIsDeleted = 0;
ent.Users.Add(reg);
ent.SaveChanges();
}
string IRegistration.Address { get; }
int IRegistration.UserId { get; }
string IRegistration.Email { get; }
string IRegistration.Password { get; }
string IRegistration.FirstName { get; }
string IRegistration.LastName { get; }
DateTime IRegistration.Birthday { get; }
DateTime IRegistration.DateCreated { get; set; }
string IRegistration.MobileNumber { get; }
int IRegistration.UserIsDeleted { get; set; }
int IRegistration.UserRoleId { get; set; }
UserRole IRegistration.UserRole { get; }
}
}
I wonder what causes this error?
While every User implements IRegistration, not every IRegistration instance is a User.
For example, your RegisterAction also implements IRegistration. So if what you wanted to do was possible, you could, in theory have this code:
RegisterAction action = GetRegisterAction();
RegisterAction action2 = new RegisterAction(action);
Which means when you come to do:
ent.Users.Add(reg);
It will fail because reg is not a User.
You could work around it like this:
var user = reg as User;
if(user != null)
{
ent.Users.Add(user);
}
But really you should probably take a look at your structure first as it seems quite odd to be doing this.
You have not told is exactly where you get the compile error but my guess is that it in the line ent.Users.Add(reg) in the Registration method.
To fix the compile error you should change the argument to the Registration method from IRegistration to User:
public void Registration(User reg)
{
reg.DateCreated = DateTime.Now;
reg.UserRoleId = 1;
reg.UserIsDeleted = 0;
ent.Users.Add(reg);
ent.SaveChanges();
}
However, this may trigger another compile error further up the call chain if you try to pass an IRegistration instead of a User to the Registration method.
While User can (and does) implement IRegistration you cannot assume that anything implementing IRegistration is an User. If your code is based on that assumption you will have to fix that to solve your problem.
I have been learning asp.net mvc for a while now and I am coming to grips with using the entity framework,
I have the following Model
[Table("User")]
public partial class User
{
// [ConcurrencyCheck]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "User Name")]
[Remote("IsUserNameAvailable", "User", ErrorMessage = "User name already Exists.")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(150, MinimumLength = 6)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string Surname { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
[Remote("IsEmailAvailable", "User", ErrorMessage = "Email Address Already Exists.")]
public string Email { get; set; }
}
This all works fine when I register a user. But my problem is that I tried Doing something like this for login
[Table("User")]
public partial class Login
{
// [ConcurrencyCheck]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
[Key]
public int Id { get; set; }
[Required]
[Display(Name = "User Name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[StringLength(150, MinimumLength = 6)]
[Display(Name = "Password")]
public string Password { get; set; }
}
The reason I wanted this was so that I can use a model that would not have to use the remote Attribute as I wouldn't be checking if the username exists
The error I get when I do this says that I cannot use separate entities for the same table. I am trying to get around not triggering the remote attribute for the login part.
Has anyone come across this?
Thanks,
remove access modifier partial
and
[Table("User")] ,[Key]
attributes
I am new to MVC 3 Data Annotations and I just want to ask that if its possible to add Validation on a Group of Fields in Model and Display the validation if none of it has Value?
this is the set of fields in my Data model
public class ContactModel
{
public Nullable<int> Id { get; set; }
[Display(Name = "Contact Firstname")]
[Required(ErrorMessage = "Required!")]
public string ContactFirstname { get; set; }
[Display(Name = "Contact Lastname")]
[Required(ErrorMessage = "Required!")]
public string ContactLastname { get; set; }
[Display(Name = "Contact Middlename")]
public string ContactMiddlename { get; set; }
[Display(Name = "Phone")]
[Required(ErrorMessage = "Required!")]
public string ContactPhone { get; set; }
[Display(Name = "Mobile ")]
[Required(ErrorMessage = "Required!")]
public string ContactMobile { get; set; }
[Display(Name = "Email")]
[Required(ErrorMessage = "Required!")]
public string ContactEmail { get; set; }
[Display(Name = "Job Title")]
[StringLength(50, ErrorMessage = "Max character reached!")]
public string ContactJobTitle { get; set; }
}
And I want to add validation if one from Phone,Mobile or Email doesn't have value
Thanks
You can implement IValidatableObject interface and add validation for all necessary properties:
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if(string.IsNullOrEmpty(Phone) || string.IsNullOrEmpty(Mobile) || string.IsNullOrEmpty(Email))
{
yield return new ValidationResult("Some error message");
}
}
Of course you should remove [Required] attributes then from those properties.
I would like to ask some help to figure out whats happening to my Login page.
I have a class named User.cs generated by EF
public partial class User
{
public User()
{
this.PersonnelInfo = new HashSet<PersonnelInfo>();
}
public int UserId { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public int RoleId { get; set; }
public int AccountId { get; set; }
public virtual ICollection<PersonnelInfo> PersonnelInfo { get; set; }
public virtual Role Role { get; set; }
public virtual Account Account { get; set; }
}
To add a validation to those properties I add a new class named UserMd.cs
[MetadataType(typeof(UserMetadata))]
public partial class User
{
}
public class UserMetadata
{
public int UserId { get; set; }
[Display(Name = "Username")]
[Required(ErrorMessage = "Username is required.")]
public string Username { get; set; }
[Display(Name = "Password")]
[Required(ErrorMessage = "Password is required.")]
[DataType(DataType.Password)]
public string Password { get; set; }
[Display(Name = "Role")]
[Required(ErrorMessage = "Role is required.")]
public int RoleId { get; set; }
[Display(Name = "Client ID")]
[Required(ErrorMessage = "Client ID is required.")]
public int AccountId { get; set; }
public virtual ICollection<PersonnelInfo> PersonnelInfo { get; set; }
public virtual Role Role { get; set; }
public virtual Account Account { get; set; }
}
What I wanted to do is to extend my User class properties and base on my research I can extend my User class by adding additional partial class so I create UserPropertyExtended.cs
public partial class User
{
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation do not match.")]
public string ConfirmPassword { get; set; }
}
My problem occured when I add validation to ConfirmPassword property.
I cannot Login to my application.
If I remove the validation everything is fine.
I don't want to add another column to my table that's why I extend my class User.
Hope you can help me.
Thank you.