When creating a form for a Store I have one ContactPerson and one EconomyPerson. For each of them I need the name to be required but the email should not even be visible in the form for the EconomyPerson.
I would like to use the EditorTemplate for my class Person. But can I hide input fields and change the validation requirements from the Store class?
public class Person
{
[Required]
public String FirstName { get; set; }
[Required]
public String LastName { get; set; }
[Required]
public String Email { get; set; }
[Required]
public String PhoneNumber { get; set; }
public String MobileNumber { get; set; }
}
public class Store
{
[Required]
public Person ContactPerson { get; set; }
[Required]
public Person EconomyPerson{ get; set; }
}
Related
I'm trying to create 1-to-1 relationship between two classes. 1 user has 1 profile picture and 1 profile picture belongs to one user.
the code is as follows.
public class UserImage
{
[Key, ForeignKey("User")]
public int ImageId { get; set; }
public byte [] ImageContentBytes { get; set; }
public string FileName { get; set; }
public string UserId { get; set; }
public string ImagePath { get; set; }
[InverseProperty("UserImage")]
public virtual ApplicationUser User { get; set; }
}
public class ApplicationUser : IdentityUser
{
public string FullName { get; set; }
public string Address { get; set; }
public string Postcode { get; set; }
public string RoleId { get; set; }
public IdentityRole Role { get; set; }
public int CityId { get; set; }
public ICollection<User_Has_Jobs_Posted> UserJobs { get; set; }
public City City { get; set; } // Adding relationship to the user.
public IList<JobPost> jobPosts { get; set; }
[InverseProperty("User")]
public virtual UserImage UserImage { get; set; }
}
The error is saying:
Unable to determine the principal end of an association between the types 'FinalWorkFinder.Models.UserImage' and 'FinalWorkFinder.Models.ApplicationUser'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.
In a one-to-one relationship one entry must depend on another, rather then both entries depending on each other.
So in your case an ApplicationUser entry would be valid on its own but a UserImage cannot.
You can fix this by using the Required attribute on the FK like so:
[Required]
public virtual ApplicationUser User { get; set; }
Or you could use fluent api, and do something along the lines of:
modelBuilder.Entity<ApplicationUser>()
.HasOptional(f => f.UserImage)
.WithRequired(s => s.User);
I have 2 tables contract and account in my database, I want to modify the contract table only if the account code is in the account table.
The tables are created in the database already. I have 2 entities in my mvc application:
Contract entity:
public class Contract
{
[Key]
[HiddenInput(DisplayValue = false)]
public int ContractID { get; set; }
[Display(Name = "Account Code")]
//[ForeignKey("AccountCode")]
public string AccountCode { get; set; }
//public virtual Account AccountCode { get; set; }
[Display(Name = "Product Code")]
public string ProductCode { get; set; }
}
In my Accounts entity:
public class Accounts
{
[Key]
public string AccountCode { get; set; }
public string CompanyName { get; set; }
public string CompanyNumber { get; set; }
public string VATNumber { get; set; }
public string Telephone { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string County { get; set; }
public string PostCode { get; set; }
public string Country { get; set; }
//public virtual ICollection<Contract> Contract { get; set; }
}
The CRUD is working currently without the foreign keys as I have commented them out.
I have a foreign key (AccountCode)in the database on the contract table linking to the accounts table. How do I implement that on my mvc application with my entities above?
I have read google and tried the commentted code above without any success.
Thanks in advance for your help
This will do it for you
public class Contract
{
[Key]
[HiddenInput(DisplayValue = false)]
public int ContractID { get; set; }
public virtual Account Account{ get; set; }
[Display(Name = "Product Code")]
public string ProductCode { get; set; }
public string AccountAccountCode {get;set;}
//automatically treated as foreign key of Account[Notice ClassNameKey Format]
}
I have the following model for an article.
public class Article
{
[Key]
public int ArticleId { get; set; }
[Required(ErrorMessage = "Title is required."), MaxLength(80)]
public string Title { get; set; }
[Required(ErrorMessage = "Body is required.")]
public string Body { get; set; }
public DateTime Time { get; set; }
public int AuthorId { get; set; }
// Navigation properties
public virtual UserProfile Author { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
The UserProfile is an extendend version of the default in the MVC4 standard project.
Now, in my scaffolded controller/view, there is no way to enter the Author.
My database (MySQL) contains a field with named Author_UserId of type int.
What is wrong?
Also, is it really necessary for the author to be referenced both via the navigation property and the AuthorId
It's not common to use 2 the same Foreign keys of a specific table at any table. Such this interpreted as data redundancy. To solve the problem without any redundancy, i suggest bellow model to you:
public class Article
{
[Key]
public int ArticleId { get; set; }
[Required(ErrorMessage = "Title is required."), MaxLength(80)]
public string Title { get; set; }
[Required(ErrorMessage = "Body is required.")]
public string Body { get; set; }
public DateTime Time { get; set; }
public int AuthorId { get; set; }//determine name of foreign key here of type primary key of navigatable table
// Navigation properties
[ForeignKey("AuthorId")]
public virtual UserProfile Author { get; set; }//column with name 'AuthorId'
public virtual ICollection<Tag> Tags { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
Solution above, used to self naming navigation property foreign key.
I wish be useful.
I am quite new to MVC. I am using an interface as a property for my model.
I noticed that my Data Annotation Attributes were being ignored. I also got an error while submitting the form:
Cannot create an instance of an interface.
I soon figured out that I will have to use a custom ModelBinder
I am having hard time figuring what needs to be done inside the CreateModel method of the ModelBinder
I have the following RegistrationModel:
public class RegistrationModel
{
#region Properties (8)
public string Email { get; set; }
public string FirstName { get; set; }
public Gender Gender { get; set; }
public string LastName { get; set; }
public string Password { get; set; }
public string PasswordConfirmation { get; set; }
public IPlace Place { get; set; }
public string Username { get; set; }
#endregion Properties
}
Here is the IPlace interface and implementation:
public interface IPlace
{
#region Data Members (7)
string City { get; set; }
string Country { get; set; }
string ExternalId { get; set; }
Guid Id { get; set; }
string Name { get; set; }
string Neighborhood { get; set; }
string State { get; set; }
#endregion Data Members
}
public class Place : IPlace
{
#region Implementation of IPlace
public Guid Id { get; set; }
[StringLength(100, ErrorMessage = "City is too long.")]
public string City { get; set; }
[StringLength(100, ErrorMessage = "Country is too long.")]
public string Country { get; set; }
[StringLength(255, ErrorMessage = "External ID is too long.")]
public string ExternalId { get; set; }
[Required(ErrorMessage = "A name is required.")]
[StringLength(450, ErrorMessage = "Name is too long.")]
[DisplayName("Location")]
public string Name { get; set; }
[StringLength(100, ErrorMessage = "Neighborhood is too long.")]
public string Neighborhood { get; set; }
[StringLength(100, ErrorMessage = "State is too long.")]
public string State { get; set; }
#endregion
}
You should try to avoid using interfaces and abstract types in your view models. So in your case if the controller action taking this view model can never have any other implementation of IPlace than Place, than simply replace the interface.
If for some reason you needed it, as you have already found out, you will have to write a custom model binder in which you specify which implementation you want to create. Here's an example.
I have a situation where I need to validate a child, but only if it exists. Basically the user can enter either a bank account or a credit card, and I only want to validate the one they enter.
Here are the Models:
public class AccountViewModel
{
[Required]
public bool isBankAccount { get; set; }
[RequiredIf("isBankAccount")]
public BankAccount BankAccount { get; set; }
[RequiredIf("isBankAccount",
IfNot = true)]
public CreditCard CreditCard { get; set; }
}
public class CreditCard
{
[Required]
[CreditCard]
public string CreditCardNumber { get; set; }
[Required]
[Range(1, 12)]
public int? ExpiryMonth { get; set; }
[Required]
[Range(2000, 3000)]
public int? ExpiryYear { get; set; }
[Required]
public string CardHolderName { get; set; }
}
public class BankAccount
{
[Required]
public string BSB { get; set; }
[Required]
[StringLength(10,
MinimumLength = 3)]
[NumbersOnly]
public string AccountNumber { get; set; }
[Required]
public string AccountHolderName { get; set; }
}
My problem is that the children's attributes are still being validated despite the parent attribute validating as true. Is there a way to stop the children from validating if the parent says so?
Why not make a property PaymentMode , derive both Bank and CC from PaymentMode, make the field required, and handle it in UI as to what user can select and enter.
Just a thought.