I am facing an issue when validating a form on ASP.
I have 2 models Person and Address. Each of them have their specific forms to add entries using EF Core.
In Person form I need hidden inputs to keep track of potential Address related data (It is perfectly fine there is no Address). To that matter I use hidden input fields but because the Address model have validation annotations, the generated markup reflects it which puts ModelState.IsValid to false upon validation unless, of course, I am editing a person with valid Address data.
I also tried to set Person.Address to null in the specific situation where it should be just before actually checking its value and it does not work. Probably it is already too late for ModelState to update by then.
if (Person.Address is not null && Person.Address.Id == 0)
Person.Address = null;
if (ModelState.IsValid)
// Further code to save data in DB
else
// Code to redisplay the page
I would like to know if there is a way to tell ASP not to validate/ignore specific input fields but still allow me to keep a piece of data?
Thank you very much.
Edit:
As per demand in the comments I add the classes with annotation
The Person
public class Person
{
[Key]
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Range(0, 150)]
public int Age { get; set; }
public Address Address { get; set; }
}
The address class
public class Address
{
[Key]
public int Id { get; set; }
[Required, MaxLength(50)]
public string Street { get; set; }
[Required, MaxLength(50)]
public string City { get; set; }
[Required, MaxLength(50)]
public string Country { get; set; }
}
OK Problem solved. I found some interesting doc.
Thanks for the propositions.
You can skip data annotations on those fields which you don't want to validate.
My project is web apllication on ASP.NET MVC 6
and basicaly I have a realy weird problem.
This is the code:
await Dashboards.UpdateReward(dashboard);
await Lessons.Update(lesson);
methods don't do anything specific but save modified states to database.
Here is what the problem is. When I start application normally and run through this part of the code it throws error:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
But here is the tricky part when I debug it and go step by step it works just fine without any error.
You may want to take a look at this to find more information about your exception:
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details
Thank you for your help. It would seem that the problem was in dashboard model. Lazzy loading didnt load my User property and since it is foreign key it can not be null value.
[Key, ForeignKey("User")]
public string UserId { get; set; }
//Gemification
public int Level { get; set; }
public int Experience { get; set; }
public int Yens { get; set; }
//Application
[Column(TypeName = "datetime2")]
public DateTime Created { get; set; }
[Column(TypeName = "datetime2")]
public DateTime Updated { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public virtual ICollection<Lesson> Lessons { get; set; }
public virtual ICollection<OwnedGroup> OwnedGroups { get; set; }
[Required]
public virtual ApplicationUser User { get; set; }
Any way thank you for your help.
I'm trying to get information from some of my models that have a foreign key relationships to my main employee model. If I map out each model individually, I can access them like normal with no problems, but I have to visit multiple different web pages to do so.
I'm trying to merge several of my models into essentially a single controller, and work with them this way. Unfortunately, when I try to access these models I get a strange error:
System.Data.SqlClient.SqlException: Invalid column name 'phone_types_phone_type_id'.
After searching through my code, apparently the only location phone_types_phone_type_id appears is in my migration code. I'm incredibly new at C# and Asp.Net in general so any help is appreciated.
Here is the code for my model:
[Table("employee.employees")]
public partial class employees1
{
public employees1()
{
employee_email_manager = new List<email_manager>();
employee_employment_history = new HashSet<employment_history>();
employee_job_manager = new HashSet<job_manager>();
employee_phone_manager = new HashSet<phone_manager>();
this.salaries = new HashSet<salary>();
}
[Key]
public int employee_id { get; set; }
[Display(Name="Employee ID")]
public int? assigned_id { get; set; }
[Display(Name="Web User ID")]
public int? all_id { get; set; }
[Required]
[StringLength(50)]
[Display(Name="First Name")]
public string first_name { get; set; }
[StringLength(50)]
[Display(Name="Last Name")]
public string last_name { get; set; }
[Column(TypeName = "date")]
[Display(Name="Birthday")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime birth_day { get; set; }
[Required]
[StringLength(1)]
[Display(Name="Gender")]
public string gender { get; set; }
[Required]
[StringLength(128)]
[Display(Name="Social")]
public string social { get; set; }
[Required]
[StringLength(128)]
[Display(Name="Address")]
public string address_line_1 { get; set; }
[StringLength(50)]
[Display(Name="Suite/Apt#")]
public string address_line_2 { get; set; }
[Required]
[StringLength(40)]
[Display(Name="City")]
public string city { get; set; }
[Required]
[StringLength(20)]
[Display(Name="State")]
public string state { get; set; }
[Required]
[StringLength(11)]
[Display(Name="Zip")]
public string zip { get; set; }
[Column(TypeName = "date")]
[Display(Name="Hire Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime hire_date { get; set; }
[Column(TypeName = "date")]
[Display(Name="Separation Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime? termination_date { get; set; }
[StringLength(70)]
[Display(Name="Emergency Contact Name")]
public string emergency_contact_name { get; set; }
[StringLength(15)]
[Display(Name = "Emergency Contact Number")]
public string emergency_contact_phone { get; set; }
[Display(Name = "Notes")]
public string notes { get; set; }
public virtual ICollection<phone_manager> employee_phone_manager { get; set; }
[Table("employee.phone_manager")]
public partial class phone_manager
{
[Key]
public int phone_id { get; set; }
public int employee_id { get; set; }
[Required]
[StringLength(15)]
public string phone_number { get; set; }
[StringLength(5)]
public string phone_extension { get; set; }
public int phone_type { get; set; }
[Column(TypeName = "date")]
public DateTime date_added { get; set; }
public bool deleted { get; set; }
public virtual employees1 employees1 { get; set; }
public virtual phone_types phone_types { get; set; }
}
[Table("employee.phone_types")]
public partial class phone_types
{
public phone_types()
{
phone_manager = new HashSet<phone_manager>();
}
[Key]
public int phone_type_id { get; set; }
[Required]
[StringLength(50)]
public string phone_type_name { get; set; }
public virtual ICollection<phone_manager> phone_manager { get; set; }
}
}
And the pertinent code from my view:
#foreach (var item in Model.employee_phone_manager)
{
#Html.DisplayFor(modelItem => item.phone_number);
#: -
#Html.DisplayFor(modelItem => item.phone_type);
<br />
}
EDIT I may have found out the issue, but I'll definitely take more input if there is another option. My solution was to take and add the following: [ForeignKey("phone_type")] directly above this line: public virtual phone_types phone_types { get; set; } in my phone_manager class.
Your issue is that your connection string in data layer and connection string in web layer are pointing to different databases.
e.g.
data layer reading dev database
webapp pointing to test database.
Either update connection strings to point to the same database.
or
Make sure your both database have same tables and columns.
After doing quite a bit more research, it seems like I had a fairly unique issue. I attempted several of the fixes listed both on here and many other sites, but almost nothing seemed to fix the issue.
However, the solution I listed at the bottom of my original post seems to be working, and holding up well, so I believe it to be a fairly adequate solution to my problem.
To somewhat outline what was occurring, MVC EF was attempting to find a fk/pk relationship across two models, but since the column names across the models were different, it wasn't able to map them properly. If I were to trying to get all the emails from email_manager by using the email_types table, it wasn't an issue, but moving backwards, and grabbing the information from email_types from email_manager threw errors.
Since the column names between the two tables are different, EF tried to create a column to house the relationship, but since no such column existed, an error was thrown. To correct this, all that's necessary is to tell EF what the foreign key column actually is, and that is done by using [ForeignKey("email_type")] above the collection that houses the parent model.
So for example, my new email_types and email_manager models were as follows:
[Table("employee.email_manager")]
public partial class email_manager
{
[Key]
public int email_id { get; set; }
public int employee_id { get; set; }
[Required]
[StringLength(255)]
public string email { get; set; }
public int email_type { get; set; }
[Column(TypeName = "date")]
public DateTime date_added { get; set; }
public bool deleted { get; set; }
[ForeignKey("email_type")]
public virtual email_types email_types { get; set; }
public virtual employees1 employees1 { get; set; }
}
[Table("employee.email_types")]
public partial class email_types
{
public email_types()
{
email_manager = new HashSet<email_manager>();
}
[Key]
public int email_type_id { get; set; }
[Required]
[StringLength(50)]
public string email_type_name { get; set; }
public virtual ICollection<email_manager> email_manager { get; set; }
}
I had the similar issue. What happens is that in the database foreign keys are created and it starts mapping both the models and then throws an exception. Best way is to avoid foreign key creation by using [NotMapped] as you could use complex models and also avoid creation of Foreign Key.
You have specify the Database Table using [Table("employee.employees")]. Check your database Table is there have a column that name is phone_types_phone_type_id .It Try to find data of that column but It did not find column then throw this Message. My Problem has solve Check my database database Table.
I'm using nop commerce and to get around my problem I had to use ignore in my database map
Ignore(p => p.CategoryAttachmentType);
In the domain I had
/// <summary>
/// Gets or sets the category attachment type
/// </summary>
public CategoryAttachmentType CategoryAttachmentType
{
get
{
return (CategoryAttachmentType)this.CategoryAttachmentTypeId;
}
set
{
this.CategoryAttachmentTypeId = (int)value;
}
}
I came across the same kind of exception. My solution is to go to the model class and verify the exception given property definition/type where it defines. In here better check the Model class/classes where you define 'phone_types_phone_type_id'.
You are right.
I had similar issue.
Something like this
[ForeignKey("StatesTbl")]
public int? State { get; set; }
public StatesTbl StateTbl { get; set; }
So as you can see, I had kept name 'StateTbl' in the last line instead of 'StatesTbl'
and app kept looking for StateTblID. Then I had to change name to 'StatesTbl' instead. And then it started working well.
So now, my changed lines were:
[ForeignKey("StatesTbl")] <== 'StatesTbl' is my original States table
public int? State { get; set; }
public StatesTbl StatesTbl { get; set; }
These are in the AppDbContext.cs class file
I had an issue where I was getting the same error and I resolved it by deleting the audit trail I had created and creating a new one. I had forgotten to do this when I deleted some columns from the table earlier on.
My problem is that I forgot that I've created several SQL Views in my database.
I've used those views in my ASP.NET C# MVC app.
So when I received error I naturally checked all databases tables but forgot about views in which I didn't add new fields.
Hi I am following the steps from this tutorial :
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
When I try to add a controller that use one of my models , I get this warning:
This is the model based on witch I am tryng to create the controller:
public class Student
{
public int StudentID { get; set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual ICollection<Enrollment> Enrollments { get; set; }
}
And this are the setting that I am adding when I try to create it :
I am not really sure what that warning is telling so I do not know If I posted the correct information needed in order to solve it.If anything else is needed I will post it later.
How can I solve this problem?
For some reason changing the provider from System.Data.SqlServerCe.4.0 to System.Data.SqlClient seems to solve this problem.
I'm currently writing a billing application using EF 5 Code First, and I'm running into an error when I'm running the application.
The database object in question is as follows:
[Table("Client")]
public class ClientBase
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClientID { get; set; }
[Required]
public string ClientName { get; set; }
[Required]
public bool IsActive { get; set; }
[Required]
public string ClientContactName { get; set; }
[Required]
public string ClientContactEmail { get; set; }
[Required]
public DateTime ClientStartDate { get; set; }
[Required]
public string SalesforceID { get; set; }
public DateTime TerminatedDate { get; set; }
public string ClientStreet { get; set; }
public string ClientCity { get; set; }
public string ClientState { get; set; }
public int? ClientZipCode { get; set; }
public virtual List<PropertyBase> Properties { get; set; }
public virtual List<ClientCharge> ClientDefaultCharges { get; set; }
}
I recently added a bunch of those fields (From ClientStartDate down to ClientZipCode are all new), and whenever I run the application I get the following error:
{"Invalid column name 'ClientStartDate'.\r\nInvalid column name 'SalesforceID'.\r\nInvalid column name 'TerminatedDate'.\r\nInvalid column name 'ClientStreet'.\r\nInvalid column name 'ClientCity'.\r\nInvalid column name 'ClientState'.\r\nInvalid column name 'ClientZipCode'."}
What amazes me, though, is that my database actually has updated accordingly. Those fields are now on the table, but this is still giving me an error.
Any ideas for what's going wrong here?
EDIT: Ok, there apparently was one thing I forgot to mention: SalesforceID is NOT a foreign key. None of the columns that were added were actually FKs. They are just plain fields.
In short, consider making your [Required] DateTime fields Nullable (DateTime?). If you provide more information about the stacktrace and any Initialization code it would be helpful.
[Required]
public DateTime? ClientStartDate { get; set; }
In my case this error happened because I was updating my EDMX against my testing database and running my code against the production database.
My suspicion is that SalesforceID is causing the problem. Try removing all of the new columns and adding them back one at a time, checking for errors as you go. If the problem is indeed with SalesforceID, this may solve it.