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;
Related
I have 4 model in my asp.net mvc application, and I get an error when I wrote Update-Database command
Introducing FOREIGN KEY constraint 'FK_dbo.Appointments_dbo.Doctors_DoctorId' on table 'Appointments' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors.
public class Appointment
{
public Appointment()
{
Status = "UnCompleted";
}
[Display(Name = "Appointment Id")]
[Key]
public int AppoiId { get; set; }
[Display(Name = "Patient Id")]
public int PatientId { get; set; }
[ForeignKey("PatientId")]
public virtual Patient Patient { get; set; }
[Display(Name = "Clinic Id")]
public int ClinicId { get; set; }
[ForeignKey("ClinicId")]
public virtual Clinic Clinic { get; set; }
[Display(Name = "Doctor Id")]
public int DoctorId { get; set; }
[ForeignKey("DoctorId")]
public virtual Doctor Doctor { get; set; }
[Required]
[DataType(DataType.Date)]
public string Date { get; set; }
[Required]
[DataType(DataType.Time)]
public string Time { get; set; }
public string Status { get; set; }
}`public class Doctor
{
[Display(Name = "Doctor Id")]
[Key]
public int DoctorId { get; set; }
[Required(ErrorMessage ="Please Enter First Name")]
[Display(Name ="First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please Enter Last Name")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required(ErrorMessage ="Please Enter Email")]
[EmailAddress]
public string Email { get; set; }
[Required(ErrorMessage ="Please Enter Password")]
[Display(Name ="Password")]
[DataType(DataType.Password)]
[NotMapped]
public string Password { get; set; }
[Required(ErrorMessage = "Please Enter Phone number")]
[Display(Name ="Phone")]
public string Phone { get; set; }
public int ClinicId { get; set; }
[ForeignKey("ClinicId")]
public virtual Clinic Clinic { get; set; }
}`public class Clinic
{
[Key]
[Display(Name = "Clinic Id")]
public int ClinicId { get; set; }
[Required(ErrorMessage ="Please Enter Clinic Name")]
[Display(Name = "Clinic Name")]
public string ClinicName { get; set; }
[Display(Name ="No. of Doctors")]
public int No_Doctors { get; set; }
[Required]
[Display(Name ="Available Time")]
public string Available_time { get; set; }
}`public class Report
{
[Key]
public int ReportId { get; set; }
public int AppoiId { get; set; }
[ForeignKey("AppoiId")]
public virtual Appointment Appointment { get; set; }
public int PatientId { get; set; }
[ForeignKey("PatientId")]
public virtual Patient Patient { get; set; }
public int DoctorId { get; set; }
[ForeignKey("DoctorId")]
public virtual Doctor Doctor { get; set; }
[Required]
public string Symptoms { get; set; }
[Required]
public string Diagnosis { get; set; }
public string Date { get; set; }
[Required]
[Display(Name ="Report Type")]
public Type ReportType { get; set; }
}`
What is the problem ?
I have used this
public List<InspectionReport> GetInspectionReportDetails(int InspectionReportID)
{
var List= this.Database.SqlQuery<InspectionReport>("GetInspectionReportDetails", InspectionReportID).ToList();
return List;
}
in a class that is inherited from DbContext
I am calling this function in a controller but List is empty. Database.SqlQuery returns 0 items even the procedure is returning data for the parameter i am providing to the function but not this.
Update:
alter PROCEDURE GetInspectionReportDetails
#InspectionReportID int=0
AS
BEGIN
Select ir.InspectionReportID
,ir.VelosiProjectNo
,ir.VelosiReportNo
,ir.Reference
,ir.PoNo
,ir.InspectionDate
,ir.IssueDate
,ir.InspectionPhase
,ir.InServiceInspection
,ir.NewInduction
,ir.HydrostaticTest
,ir.DimensionalCheck
,ir.ThicknessCheck
,ir.Patrom
,ir.Gvs
,ir.FinalOgraInspection
,ir.OmcClientRequirement
,ir.TankLorryRegistrationNo
,ir.TruckTractorManufacturerName
,ir.ClientName
,ir.Capacity
,ir.Omc
,ir.EngineNo
,ir.TankLorryDimension
,ir.ChassisNo
,ir.InspectionPlace
,ir.TankLorryEnginePower
,ir.CarriageName
,ir.Brakes
,ir.IsSatisfactory
,ir.Remarks
,ir.Rev
,ir.Description
,ir.Status
,u1.UserName as PeparedBy
,u2.UserName as CheckedBy
,u3.UserName as ApprovedBy
,u4.UserName as IssuedBy
From InspectionReport ir
Inner Join dbo.[User] u1
ON u1.UserID= ir.PeparedBy
Inner Join dbo.[User] u2
ON u2.UserID= ir.CheckedBy
Inner Join dbo.[User] u3
ON u3.UserID= ir.ApprovedBy
Inner Join dbo.[User] u4
ON u4.UserID= ir.IssuedBy
where ir.InspectionReportID= #InspectionReportID
This is the stored procedure that is called by the function.
This the class inpsectionreport;
namespace VAILCertificates.DAL.Entities
{
public class InspectionReport
{
//General Details
public int InspectionReportID { get; set; }
[Required]
[Display (Name= "Velosi Project No")]
public string VelosiProjectNo { get; set; }
[Display(Name = "Velosi Report No")]
public string VelosiReportNo { get; set; }
[Required]
public string Reference { get; set; }
[Required]
[Display(Name = "PO No")]
public string PoNo { get; set; }
[Required]
[Display(Name = "Inspection Date")]
public DateTime InspectionDate { get; set; }
[Required]
[Display(Name = "Issue Date")]
public DateTime IssueDate { get; set; }
//Inspection Phase
[Required]
[Display(Name = "Inspection Phase")]
public byte InspectionPhase { get; set; } //0= Before, 1= During, 2= Final
//Types Of Inspection
[Display(Name = "In Service Inspection")]
public bool InServiceInspection { get; set; }
[Display(Name = "New Induction")]
public bool NewInduction { get; set; }
[Display(Name = "Hydorstatic Test")]
public bool HydrostaticTest { get; set; }
[Display(Name = "Dimensional Check")]
public bool DimensionalCheck { get; set; }
[Display(Name = "Thickness Check")]
public bool ThicknessCheck { get; set; }
[Display(Name = "PATROM")]
public bool Patrom { get; set; }
[Display(Name = "GVS")]
public bool Gvs { get; set; }
[Display(Name = "Final OGRA Inspection")]
public bool FinalOgraInspection { get; set; }
[Display(Name = "OMC/Client Requirement")]
public bool OmcClientRequirement { get; set; }
//Details Of Tank Lorry
[Required]
[Display(Name = "Tank Lorry Registration Number")]
public string TankLorryRegistrationNo { get; set; }
[Required]
[Display(Name = "Truck Tractor Manufacturer Name")]
public string TruckTractorManufacturerName { get; set; }
[Required]
[Display(Name = "Client Name")]
public string ClientName { get; set; }
[Required]
[Display(Name = "Capacity")]
public string Capacity { get; set; }
[Required]
[Display(Name = "OMC")]
public string Omc { get; set; }
[Required]
[Display(Name = "Engine No")]
public string EngineNo { get; set; }
[Required]
[Display(Name = "Tank Lorry Dimension")]
public string TankLorryDimension { get; set; }
[Required]
[Display(Name = "Chassis Number")]
public string ChassisNo { get; set; }
[Required]
[Display(Name = "Inspection Place")]
public string InspectionPlace { get; set; }
[Required]
[Display(Name = "Tank Lorry (Engine Power)")]
public string TankLorryEnginePower { get; set; }
[Required]
[Display(Name = "Carriage Name")]
public string CarriageName { get; set; }
[Required]
public string Brakes { get; set; }
//ResultsofInspection
[Required]
[Display(Name = "Is Satisfactory?")]
public bool IsSatisfactory { get; set; }
//Remarks
[Required]
public string Remarks { get; set; }
//ApprovalSection
public string Rev { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int PeparedBy { get; set; }
public int CheckedBy { get; set; }
public int ApprovedBy { get; set; }
public int IssuedBy { get; set; }
//ReportStatus
public byte Status { get; set; } //0= Prepared 1= CheckedBy 2= ApprovedBy
}
}
You can also construct a DbParameter and supply it as a parameter value to your stored procedure:
var InspectionReportID= new SqlParameter("#InspectionReportID", 0);
var list = this.Database.SqlQuery<InspectionReport>("EXECUTE dbo.GetInspectionReportDetails #InspectionReportID",InspectionReportID).ToList();
It is important to parameterize any user input to protect against a SQL injection attack. You can include parameter placeholders in the SQL query string and then supply parameter values as additional arguments. Any parameter values you supply will automatically be converted to a DbParameter.
Try changing the the sql statement, I feel the error is how you call the sql statement.
var list = this.Database.SqlQuery<InspectionReport>($"EXEC GetInspectionReportDetails {InspectionReportID}").ToList();
Try using this code:
public List<InspectionReport> GetInspectionReportDetails(int InspectionReportID)
{
var List= this.Database.SqlQuery<InspectionReport>("GetInspectionReportDetails #InspectionReportID", InspectionReportID).ToList();
return List;
}
Below is my State Model class.
public class State
{
[Key]
public int StateId { get; set; }
public string StateName { get; set; }
public virtual ICollection<City> Cities { get; set; }
}
Below is my City Model Class base state, city will fill.
public class City
{
[Key]
public int CityId { get; set; }
public string CityName { get; set; }
[ForeignKey("State")]
public int StateId { get; set; }
public virtual State State { get; set; }
}
Below is my Registration model class for the registration form which calls State city.
public class Registration
{
[Key]
public int Sno { get; set; }
[Required(ErrorMessage = "Name is required.")]
[Display(Name = "Full name")]
public string Fullname { get; set; }
[Display(Name = "Email Id")]
[Required(ErrorMessage = "Email is required.")]
public string EmailId { get; set; }
[Required(ErrorMessage = "Password is required.")]
public string Password { get; set; }
[Required(ErrorMessage = "Mobile is required.")]
public string Mobile { get; set; }
[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
public int SelectedStateId { get; set; }
public int SelectedCityId { get; set; }
[Required(ErrorMessage = "Entity is required.")]
public string EntityType { get; set; }
public string Website { get; set; }
public string PinCode { get; set; }
public string accountactivated { get; set; }
public int RoleId { get; set; }
[Display(Name = "New Password")]
[NotMapped]
public string NewPassword { get; set; }
[Display(Name = "Confirm New Password")]
[NotMapped] // Does not effect with your database
[System.Web.Mvc.Compare("NewPassword", ErrorMessage = "Password not match")]
public string ConfirmNewPassword { get; set; }
}
My question is how should i have to call state and city cascading drop down list in my Registration Model class to generate scaffolding for registration page with dependent drop down list.
Right now my POST actions for Create and Edit have rather long function definitions because there are a lot of variables and my bind attribute contains all of them.
public ActionResult Create([Bind(Include = "ProjectName,ProjectDescription,DateReceived,EffectiveDate,ExpirationDate,GeneralContractor,ProjectTerm,ProjectType,SubmissionNumber,PolicyNumber,Status,Underwriter,Division,BrokerCity,TAName,Branch,FirstNamedInsuredAddress,FirstNamedInsured,ProjectAddress")] Project project) {
and
public ActionResult Edit([Bind(Include = "ProjectID,ProjectName,ProjectDescription,DateReceived,EffectiveDate,ExpirationDate,GeneralContractor,ProjectTerm,ProjectType,SubmissionNumber,PolicyNumber,Status,Underwriter,Division,BrokerCity,TAName,Branch,FirstNamedInsuredAddress,FirstNamedInsured,ProjectAddress")] Project project) {
Is there an alternative to this that would make the definitions shorter?
Here is my model:
public class Project
{
public Project()
{
FirstNamedInsuredAddress = new Address();
ProjectAddress = new Address();
}
[Key]
public int ProjectID { get; set; }
[Required]
[StringLength(150)]
[Display(Name = "Project Name")]
public string ProjectName { get; set; }
[StringLength(1000)]
[Display(Name = "Project Description")]
public string ProjectDescription { get; set; }
[Display(Name = "Date Received")]
public string DateReceived { get; set; }
[Display(Name = "Effective Date")]
public string EffectiveDate { get; set; }
[Display(Name = "Expiration Date")]
public string ExpirationDate { get; set; }
[StringLength(150)]
[Display(Name = "General Contractor")]
public string GeneralContractor { get; set; }
[StringLength(25)]
[Display(Name = "Project Term")]
public string ProjectTerm { get; set; }
[Display(Name = "Project Type")]
public string ProjectType { get; set; }
[Required]
[Display(Name = "Submission Number")]
public long SubmissionNumber { get; set; }
[StringLength(20)]
[Display(Name = "Policy Number")]
public string PolicyNumber { get; set; }
public string Status { get; set; }
[StringLength(100)]
public string Underwriter { get; set; }
public string Division { get; set; }
[StringLength(50)]
[Display(Name = "Broker/City")]
public string BrokerCity { get; set; }
[StringLength(100)]
[Display(Name="TA Name")]
public string TAName { get; set; }
public string Branch { get; set; }
[Display(Name="First Named Insured Address")]
public Address FirstNamedInsuredAddress { get; set; }
[StringLength(150)]
[Display(Name="First Named Insured")]
public string FirstNamedInsured { get; set; }
[Display(Name="Project Address")]
public Address ProjectAddress { get; set; }
public class Address
{
[StringLength(150)]
[Display(Name="Line 1")]
public string Line1 { get; set; }
[StringLength(150)]
[Display(Name="Line 2")]
public string Line2 { get; set; }
[StringLength(100)]
public string City { get; set; }
public string State { get; set; }
[Display(Name="Zip Code")]
public int? ZipCode { get; set; }
[StringLength(100)]
public string County { get; set; }
}
}
As an alternative to the Include , you can use the Exclude. It will only exclude the properties that you do not want post. Probably, it will lesser in most of the cases or if you want, you can remove both include and exclude , and all the data will be posted .
Ex:
[HttpPost]
[ActionName("Edit")]
public ActionResult Edit([Bind(Exclude = "GeneralContractor")] Project project)
{
}
More/Useful Information:http://csharp-video-tutorials.blogspot.in/2013/05/part-21-including-and-excluding.html
I had been struggling with this issue since morning. I have the following class in my domain service.
[MetadataTypeAttribute(typeof(CompanyRecord.CompanyRecordMetadata))]
public partial class CompanyRecord
{
// This class allows you to attach custom attributes to properties
// of the CompanyRecord class.
//
// For example, the following marks the Xyz property as a
// required property and specifies the format for valid values:
// [Required]
// [RegularExpression("[A-Z][A-Za-z0-9]*")]
// [StringLength(32)]
// public string Xyz { get; set; }
internal sealed class CompanyRecordMetadata
{
// Metadata classes are not meant to be instantiated.
private CompanyRecordMetadata()
{
}
public Nullable<char> AccessToClearance { get; set; }
public Nullable<char> AccessToMarketplace { get; set; }
public Nullable<bool> Active { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public Nullable<int> AllotedHDSpace { get; set; }
public string City { get; set; }
public int CompanyID { get; set; }
public Binary CompanyLogo { get; set; }
[Required(ErrorMessage = "Company Name is required and must be unique.")]
public string CompanyName { get; set; }
[Range(1, Int32.MaxValue, ErrorMessage = "Company Type is required.")]
public int CompanyTypeID { get; set; }
[Range(1, Int32.MaxValue, ErrorMessage = "Country is required.")]
public Nullable<int> CountryID { get; set; }
public string Description { get; set; }
//[RegularExpression(pattern: #"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|tv|COM|ORG|NET|GOV|MIL|BIZ|INFO|MOBI|NAME|AERO|JOBS|MUSEUM|TV|Com|Org|Net|Gov|Mil|Biz|Info|Mobi|Name|Aero|Jobs|Museum|Tv)\b", ErrorMessage = "Please provide a valid email address")]
[RegularExpression(pattern: #"(\w[-._\w]*\w#\w[-._\w]*\w\.[a-zA-z]{2,6})", ErrorMessage = "Please provide a valid email address")]
public string EmployeeEmail { get; set; }
//[RegularExpression(pattern: #"[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum|tv|COM|ORG|NET|GOV|MIL|BIZ|INFO|MOBI|NAME|AERO|JOBS|MUSEUM|TV|Com|Org|Net|Gov|Mil|Biz|Info|Mobi|Name|Aero|Jobs|Museum|Tv)\b", ErrorMessage = "Please provide a valid email address")]
//(\w[-._\w]*\w#\w[-._\w]*\w\.\w{2,3})
[RegularExpression(pattern: #"(\w[-._\w]*\w#\w[-._\w]*\w\.[a-zA-z]{2,6})", ErrorMessage = "Please provide a valid email address")]
[Required(ErrorMessage = "Email is required.")]
public string Email { get; set; }
[StringLength(10, ErrorMessage = "Phone Ext. should not be more than 10 chars.")]
public string EmployeePhoneExt { get; set; }
[StringLength(20, ErrorMessage = "Phone No. should not be more than 20 chars.")]
[RegularExpression(pattern: #"^[0-9\-\(\) ]*[0-9\-\(\)]*$", ErrorMessage = "Please provide a valid Phone No.")]
public string EmployeePhoneNo { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
[Range(0, int.MaxValue, ErrorMessage = "Number of projects should be lower than 2,147,483,647.")]
public Nullable<int> NoOfProjects { get; set; }
public Nullable<int> NoOfUsers { get; set; }
[StringLength(10, ErrorMessage = "Phone Ext. should not be more than 10 chars.")]
public string PhoneExt { get; set; }
[StringLength(20, ErrorMessage = "Phone No. should not be more than 20 chars.")]
[Required(ErrorMessage = "Phone No. is required.")]
[RegularExpression(pattern: #"^[0-9\-\(\) ]*[0-9\-\(\)]*$", ErrorMessage = "Please provide a valid Phone No.")]
public string PhoneNo { get; set; }
[RegularExpression(pattern: #"^[a-zA-Z0-9\-\(\)\* ]*[a-zA-Z0-9\-\(\)\*]*$", ErrorMessage = "Postal codes cant' contain special characters except for -, (, ), * and spaces.")]
public string PostalCode { get; set; }
public string Province { get; set; }
public string Website { get; set; }
public int MarketID { get; set; }
public int AffiliationID { get; set; }
public string CallLetter { get; set; }
}
}
PROBLEM: I need to create a validation rule that woudl require MarketID and Affiliation ID only when CompanyTypeID is equivalent to 1, 3, 5, 9 and 11 is there someone out there who has an idea on how to solve this?
You should use the custom validation.
There are some topics for your question below:
1 http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.customvalidationattribute(vs.95).aspx
2 http://blogs.microsoft.co.il/blogs/bursteg/archive/2009/04/14/net-ria-services-custom-validation.aspx