Entity Framework Code First , Error in migration - c#

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 ?

Related

Mapping ViewModel to related entities

I have a ViewModel with several properties (VM for multi-step wizard):
public class CallViewModel
{
[Key]
[Column(Order = 0)]
[HiddenInput(DisplayValue = false)]
public System.Guid CallID { get; set; }
[Required, Display(Name = "Call Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MM yyyy} г.")]
public System.DateTime CallDate { get; set; }
[Required, Display(Name = "Contract Number")]
public string Number { get; set; }
[Display(Name = "Date of Sampling"), DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MM yyyy} г.")]
public System.DateTime SampleActDate { get; set; }
[Display(Name = "Date of the Contract"), DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MM yyyy} г.")]
public System.DateTime ContractDate { get; set; }
[Required, Display(Name = "Cost Efficiency, %")]
public decimal CostEfficiency { get; set; }
[Required, Display(Name = "Document Type")]
public string CallName { get; set; }
//Representative
[Required, Display(Name = "Second Name")]
public string RepFamilyName { get; set; }
[Required, Display(Name = "First Name")]
public string RepFirstName { get; set; }
[Required, Display(Name = "Middle Name")]
public string RepMidName { get; set; }
[Required, Display(Name = "Position")]
public string RepPosition { get; set; }
[Required, Display(Name = "Document")]
public string DocType { get; set; }
[Required, Display(Name = "Phone (###) ###-##-##")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:(###) ###-##-##}")]
public string RepPhoneNumber { get; set; }
//Customer
[Required, Display(Name = "Judicial Status")]
public string JudicialStatus { get; set; }
[Required, Display(Name = "Customer Name")]
public string CustomerName { get; set; }
[Required, Display(Name = "Address")]
public string CustomerAddress { get; set; }
[Required, Display(Name = "TaxID")]
public string TaxID { get; set; }
[Display(Name = "BIC")]
public string BIC { get; set; }
[Required, Display(Name = "PHone Number (###) ###-##-##")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:(###) ###-##-##}")]
public string CustomerPhoneNumber { get; set; }
[Required, Display(Name = "OKPO")]
public int OKPO { get; set; }
[Required, Display(Name = "Account)]
public string CustomerBankAccount { get; set; }
[Required, Display(Name = "Bank Branch")]
public string BankBranch { get; set; }
[Required, Display(Name = "Bank Address")]
public string BranchAddress { get; set; }
[Display(Name = "Bank Code")]
public Nullable<int> BankCode { get; set; }
[Display(Name = "Cell Phone Number")]
public string MPhoneNumber { get; set; }
//Person
[Required, Display(Name = "Expert")]
//public string Exp { get; set; }
public Guid ExpID { get; set; }
[Required, Display(Name = "Affidavit Number")]
public int AffidavitNum { get; set; }
[Required, Display(Name = "Affidavit Date"),
DataType(DataType.Date)]
public System.DateTime AffidavitDate { get; set; }
public List<ItemClass> ItemsList { get { return _items; } }
private List<ItemClass> _items = new List<ItemClass>();
public class ItemClass
{ //Item
public Guid ItemID { get; set; }
[Required, Display(Name = "Item SubType")]
public Guid ItemSubtype { get; set; }
[Required, Display(Name = "Item Name")]
public string ItemName { get; set; }
[Required, Display(Name = "Producer")]
public string ItemProducer { get; set; }
[Required, Display(Name = "Quantity")]
public int ItemQty { get; set; }
[Display(Name = "Additionals")]
public string Additional { get; set; }
[Required, Display(Name = "Program Name")]
public string ProgramNameShort { get; set; }
[Required, Display(Name = "Calc Date")]
public string calcDate { get; set; }
[Required, Display(Name = "Calc Number")]
public string calcNum { get; set; }
}
}
I also have several entities with 1:n relationships, like
public partial class Call
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Call()
{
this.CallDetails = new HashSet<CallDetail>();
}
public System.Guid CallID { get; set; }
public System.DateTime CallDate { get; set; }
public System.Guid CustomerID { get; set; }
public string DocNumber { get; set; }
public int AffidavitNum { get; set; }
public System.DateTime AffidavitDate { get; set; }
public System.DateTime ContractDate { get; set; }
public int CallStatus { get; set; }
public string DocType { get; set; }
public Nullable<decimal> Cost_Efficiency { get; set; }
public System.DateTime SampleActDate { get; set; }
public string CallName { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CallDetail> CallDetails { get; set; }
public virtual Customer Customer { get; set; }
}
and
public partial class CallDetail
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public CallDetail()
{
this.Orders = new HashSet<Order>();
}
public System.Guid CallID { get; set; }
public System.Guid ItemID { get; set; }
public int ItemQty { get; set; }
public decimal ItemTestCost { get; set; }
public System.Guid ProgramID { get; set; }
public virtual Call Call { get; set; }
public virtual Item Item { get; set; }
public virtual Program Program { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Order> Orders { get; set; }
}
to name a few.
In [HttpPost] public ActionResult Create (CallViewModel callViewModel) method I should map the ViewModel to those entities. I know that Automapper is among the best ways to perform it, but still I need to understand the principles of correct mapping of VM and related entities (Automapper examples are welcome as well :) ), and especially how to deal with navigation properties (I'm mostly worried about ID properties). Could you please show the best (or template) practice to perform it? Please, be as detailed as possible.
Thanks in advance.
Take this example:
public class ModelClass
{
public Guid Id { get; set; }
public ChildModel ChildModel { get; set; }
}
public class ViewModelClass
{
public Guid Id { get; set; }
public ChildModel ChildModel { get; set; } = new ChildModel();
}
public class ChildModel
{
public Guid Id { get; set; }
}
If you want to map your viewmodel to your model you can do:
[HttpPost]
public ActionResult Create (CallViewModel callViewModel) {
var model = new ModelClass;
model.Id = callViewModel.Id;
model.ChildModel = callViewModel.ChildModel;
_context.Add(model);
_context.SaveChanges();
return RedirectToAction("Index");
}
For the use of automapper I suggest you read the AutoMapper docs :)

Confusing to create models class for cascading drop down list using MVC 5 and entity framework code first

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.

insertion of foreign key asp.net mvc

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;

Alternatives to binding model for controller action

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

Cannot convert anonymous type into my MVC model

When running a LINQ query, it runs fine and gets the expected results when I include the "result.Dump()" method. The anonymous types work fine.
However, I need to put this anonymous type inside my model and am having the following conversion problem (see image - view image with your favorite viewer).
Customer is a parent of Projects with the below models. I cannot use typed models due to the following exception in the code:
The entity or complex type 'CodeFirstNamespace.Customer' cannot be constructed in a LINQ to Entities query.
namespace YeagerTechDB.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
[Serializable, DataContract(IsReference = true)]
public partial class Customer
{
public Customer()
{
Projects = new HashSet<Project>();
}
[Key]
[ScaffoldColumn(true)]
[Display(Name = "ID")]
[DataMember]
public short CustomerID { get; set; }
[Required]
[StringLength(256)]
[DataMember]
public string UserName { get; set; }
[Required]
[StringLength(50)]
[EmailAddress]
[DataMember]
public string Email { get; set; }
[StringLength(50)]
[DataMember]
public string Company { get; set; }
[StringLength(50)]
[DataMember]
public string FirstName { get; set; }
[StringLength(50)]
[DataMember]
public string LastName { get; set; }
[StringLength(50)]
[DataMember]
public string Address1 { get; set; }
[StringLength(50)]
[DataMember]
public string Address2 { get; set; }
[StringLength(50)]
[DataMember]
public string City { get; set; }
[StringLength(2)]
[DataMember]
public string State { get; set; }
[StringLength(10)]
[DataType(DataType.PostalCode)]
[RegularExpression(#"^\d{5}(-\d{4})?$", ErrorMessage = "Must match 99999 or 99999-9999 format")]
[DataMember]
public string Zip { get; set; }
[StringLength(12)]
[DataType(DataType.PhoneNumber)]
[RegularExpression(#"^\s*([\(]?)\[?\s*\d{3}\s*\]?[\)]?\s*[\-]?[\.]?\s*\d{3}\s*[\-]?[\.]?\s*\d{4}$", ErrorMessage = "Must match 999-999-9999 format")]
[DataMember]
public string HomePhone { get; set; }
[StringLength(12)]
[DataType(DataType.PhoneNumber)]
[RegularExpression(#"^\s*([\(]?)\[?\s*\d{3}\s*\]?[\)]?\s*[\-]?[\.]?\s*\d{3}\s*[\-]?[\.]?\s*\d{4}$", ErrorMessage = "Must match 999-999-9999 format")]
[DataMember]
public string CellPhone { get; set; }
[StringLength(100)]
[DataType(DataType.Url)]
[DataMember]
public string Website { get; set; }
[StringLength(50)]
[DataType(DataType.Url)]
[DataMember]
public string IMAddress { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Created")]
[DataMember]
public DateTime CreatedDate { get; set; }
[Display(Name = "Updated")]
[DataType(DataType.DateTime)]
[DataMember]
public DateTime? UpdatedDate { get; set; }
[DataMember]
public virtual ICollection<Project> Projects { get; set; }
}
}
namespace YeagerTechDB.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Runtime.Serialization;
[Serializable, DataContract(IsReference = true)]
public partial class Project
{
[Key]
[ScaffoldColumn(false)]
[Editable(false)]
[Display(Name = "Proj ID")]
[DataMember]
public short ProjectID { get; set; }
[ScaffoldColumn(false)]
[Editable(true)]
[Display(Name = "Cust ID")]
[DataMember]
public short CustomerID { get; set; }
[Required(ErrorMessage = "Required!")]
[StringLength(30)]
[Display(Name = "Project Name")]
[DataMember]
public string Name { get; set; }
[Required]
[DataType(DataType.MultilineText)]
[DataMember]
public string Description { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "Category")]
[DataMember]
public short CategoryID { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "Priority")]
[DataMember]
public short PriorityID { get; set; }
[ScaffoldColumn(true)]
[Display(Name = "Status")]
[DataMember]
public short StatusID { get; set; }
[DataType(DataType.Currency)]
[DataMember]
public decimal? Quote { get; set; }
[DataType(DataType.MultilineText)]
[DataMember]
public string Notes { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Created")]
[DataMember]
public DateTime CreatedDate { get; set; }
[DataType(DataType.DateTime)]
[Display(Name = "Updated")]
[DataMember]
public DateTime? UpdatedDate { get; set; }
[DataMember]
public virtual Category Category { get; set; }
[DataMember]
public virtual Customer Customer { get; set; }
[DataMember]
public virtual Priority Priority { get; set; }
[DataMember]
public virtual Status Status { get; set; }
[DataMember]
public virtual ICollection<TimeTracking> TimeTrackings { get; set; }
}
}

Categories