Cannot update multiple tables though no error occurs - c#

I have following parent class which has multiple child classes. I have successfully created and retrieved data from SQL database. Now I want to update record by using FormCollection.
public class UserDetailContext : DbContext
{
public UserDetailContext()
: base("DefaultConnection")
{
}
public DbSet<UserDetails> UserDetails { get; set; }
public DbSet<PersonalDetails> PersonalDetails { get; set; }
public DbSet<HoroscopeDetails> HoroscopeDetails { get; set; }
public DbSet<Expectations> Expectations { get; set; }
public DbSet<FamilyDetails> FamilyDetails { get; set; }
public DbSet<AddressDetails> AddressDetails { get; set; }
public DbSet<EducationalDetails> EducationalDetails { get; set; }
}
public class UserDetails
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public List <PersonalDetails> PdetailsList { get; set; }
public List<HoroscopeDetails> HDetailsList { get; set; }
public List<EducationalDetails> EDetailsList { get; set; }
public List<AddressDetails> AdddetailsList { get; set; }
public List<FamilyDetails> FDetailsList { get; set; }
public List<Expectations> ExpDetailsList { get; set; }
public PersonalDetails Pdetails { get; set; }
public HoroscopeDetails HDetails { get; set; }
public EducationalDetails EDetails { get; set; }
public AddressDetails Adddetails { get; set; }
public FamilyDetails FDetails { get; set; }
public Expectations ExpDetails { get; set; }
public UserDetails()
{
Pdetails = new PersonalDetails();
HDetails = new HoroscopeDetails();
EDetails = new EducationalDetails();
Adddetails = new AddressDetails();
FDetails = new FamilyDetails();
ExpDetails = new Expectations();
}
}
public class PersonalDetails
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order = 0)]
public int PersonalID { get; set; }
public int UserId { get; set; }
public string RegID { get; set; }
public string FirstName { get; set; }
public string MidName { get; set; }
public string LastName { get; set; }
}
public class HoroscopeDetails
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public string Rashi { get; set; }
public int PersonalID { get; set; }
[ForeignKey("PersonalID")]
public virtual PersonalDetails Product { get; set; }
}
public class EducationalDetails
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column(Order = 0)]
public int EduID { get; set; }
public string EducationDetails { get; set; }
public string Education { get; set; }
public int PersonalID { get; set; }
[ForeignKey("PersonalID")]
public virtual PersonalDetails Product { get; set; }
}
public class AddressDetails
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AddId { get; set; }
public int PersonalID { get; set; }
[ForeignKey("PersonalID")]
public virtual PersonalDetails Product { get; set; }
}
public class FamilyDetails
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int FId { get; set; }
public int PersonalID { get; set; }
[ForeignKey("PersonalID")]
public virtual PersonalDetails Product { get; set; }
}
public class Expectations
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ExpId { get; set; }
public int PersonalID { get; set; }
[ForeignKey("PersonalID")]
public virtual PersonalDetails Product { get; set; }
}
Now from controller I want to update a record
public void UpdateRecord(FormCollection coll)
{
int id = Convert.ToInt32(Session["UserId"]);
UserDetails obj = db.UserDetails.FirstOrDefault(s => s.UserId.Equals(id));
obj.Pdetails.FirstName = "xxxx";
obj.Pdetails.LastName = "xxxx";
obj.UserId = Convert.ToInt32(Session["UserId"]);
db.Entry(obj).State = EntityState.Modified;
int result = db.SaveChanges();
}
It doesn't give any error but also doesn't update any record.
And obj object also contains null values by following code:
UserDetails obj = db.UserDetails.FirstOrDefault(s => s.UserId.Equals(id));

Related

Get All data from two tables in .net 5 web api?

Patient.cs //This is Patient Model Class
namespace HMS.Models
{
public class Patient
{
[Key]
public string Id { get; set; }
public string Name { get; set; }
public int age { get; set; }
public int Weight { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string PhoneNo { get; set; }
public string Disease { get; set; }
[JsonIgnore]
public IList<DoctorPatient> DoctorPatients { get; set; }
public InPatient InPatients { get; set; }
public OutPatient OutPatients { get; set; }
}
}
InPatient.cs //This InPatient Model Class
namespace HMS.Models
{
public class InPatient
{
[ForeignKey("Patient")]
public string InPatientId { get; set; }
public string RoomNo { get; set; }
public DateTime DateOfAddmission { get; set; }
public DateTime DateOfDischarge { get; set; }
public int Advance { get; set; }
public string LabNo { get; set; }
public Patient Patient { get; set; }
}
}
Here Patient and InPatient Attribute have one-to-one relationship
ViewInPatient.cs
namespace HMS.Models
{
public class ViewInPatient
{
public string Name { get; set; }
public int age { get; set; }
public int Weight { get; set; }
public string Gender { get; set; }
public string Address { get; set; }
public string PhoneNo { get; set; }
public string Disease { get; set; }
public string RoomNo { get; set; }
public DateTime DateOfAddmission { get; set; }
public DateTime DateOfDischarge { get; set; }
public int Advance { get; set; }
public string LabNo { get; set; }
}
}
Here is my DbContext class
public class ApplicationDbContext:DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<DoctorPatient>()
.HasOne(x => x.Doctor)
.WithMany(dp => dp.DoctorPatients)
.HasForeignKey(di => di.DoctorId);
modelBuilder.Entity<DoctorPatient>()
.HasOne(y => y.Patient)
.WithMany(dp => dp.DoctorPatients)
.HasForeignKey(pi => pi.PatientId);
}
public DbSet<Patient> Patients { get; set; }
public DbSet<Doctor> Doctors { get; set; }
public DbSet<DoctorPatient> DoctorPatients { get; set; }
public DbSet<InPatient> InPatients { get; set; }
//public DbQuery<ViewInPatient> ViewInPatients { get; set; }
}
How to get all data of both Patients and InPatients Table like in ViewInPatient class? (I tried to create a view in sql server but in add table window it shows InPatient instead of InPatients and it return null value)
You can join both models in a Linq expression and return ViewInPatient list:
var ViewInPatient_set =
YourContext
.InPatients
.Select(i=> new ViewInPatient()
{
Name = i.Patient.Name,
// ...
RoomNo = i.RoomNo,
// ...
}
)
.ToList(); // <-- transform to list is optional

How to add a list of objects inside a list in C# MVC

I have a view model containing list of sections like below. I need to create a list of ResponseEntryViewModel and add sections and sub sections inside sections and questions inside subsections.
Any suggestions?
public class ResponseEntryViewModel
{
public int TypeID { get; set; }
public string TypeName { get; set; }
public int User_ID { get; set; }
public List<SectionDataModel> Sections{ get; set; }
public ResponseEntryViewModel()
{
Sections = new List<SectionDataModel>();
}
public class SectionDataModel
{
public int SectionID { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public int TypeId { get; set; }
public List<SubSectionModel> SubSections { get; set; }
public SectionDataModel()
{
SubSections = new List<SubSectionModel>();
}
}
public class SubSectionModel
{
public int SubSectionID { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public int SectionId { get; set; }
public List<QuestionModel> QuestionsList { get; set; }
public SubSectionModel()
{
QuestionsList = new List<QuestionModel>();
}
}
public class QuestionModel
{
public int SubSectionID { get; set; }
public int QuestionID { get; set; }
public string Question { get; set; }
}
}
Try this:
public class ResponseEntryViewModel
{
public int TypeID { get; set; }
public string TypeName { get; set; }
public int User_ID { get; set; }
public List<SectionDataModel> Sections { get; set; }
public ResponseEntryViewModel(SectionDataModel obj)
{
Sections = new List<SectionDataModel>();
Sections.Add(obj);
}
public class SectionDataModel
{
public int SectionID { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public int TypeId { get; set; }
public List<SubSectionModel> SubSections { get; set; }
public SectionDataModel(SubSectionModel obj)
{
SubSections = new List<SubSectionModel>();
SubSections.Add(obj);
}
}
public class SubSectionModel
{
public int SubSectionID { get; set; }
public string Name { get; set; }
public string Status { get; set; }
public int SectionId { get; set; }
public List<QuestionModel> QuestionsList { get; set; }
public SubSectionModel(QuestionModel obj)
{
QuestionsList = new List<QuestionModel>();
QuestionsList.Add(obj);
}
}
public class QuestionModel
{
public int SubSectionID { get; set; }
public int QuestionID { get; set; }
public string Question { get; set; }
}
}

EF Code first not creating table with npgsql

I am using EF code first with Npgsql. Everything is fine till i try to save changes using contextclassObj
public class EmployeeRepository
{
private ESAppraisalcontext DBAccessObj = null;
public EmployeeRepository()
{
DBAccessObj = new ESAppraisalcontext();
DBAccessObj.Employees.Add(new Employee { EmployeeCode = "1", EmployeeName = "shuk" });
DBAccessObj.SaveChanges();
}
}
At the point SaveChanges() it gives an exception that the Relation \ ESTables.Employee\ doesnot exist.Here is my context class :
public class ESAppraisalcontext : DbContext
{
public DbSet<Entity> Entities { get; set; }
public DbSet<Employee> Employees { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("ESTables");
base.OnModelCreating(modelBuilder);
}
}
And my model:
public class Employee
{
[Key]
public string EmployeeCode { get; set; }
public string EmployeeName { get; set; }
public string EmailId { get; set; }
public string DomainName { get; set; }
public int DesignationId { get; set; }
public int DepartmentId { get; set; }
public string MgrCode { get; set; }
public int LocationId { get; set; }
public DateTime DOJ { get; set; }
public bool IsActive { get; set; }
public bool IsEligibleForCycle { get; set; }
public bool IsNonEligibleApprover { get; set; }
[ForeignKey("DepartmentId")]
public Departments department { get; set; }
[ForeignKey("DesignationId")]
public Designations designation { get; set; }
[ForeignKey("LocationId")]
public Locations Loation { get; set; }
}

Creating Entity Model with Cross Referencing Table

Here are my models:
public partial class NEWS
{
public NEWS()
{
}
[Key]
public int NEWSID { get; set; }
public string Title { get; set; }
public string Text { get; set; }
public string InsertDate { get; set; }
public int GroupingID { get; set; }
public virtual Subjects Subjects { get; set; }
}
public partial class Subjects
{
public Subjects()
{ this.NEWSs = new HashSet<NEWS>(); }
[Key]
public int GroupingID { get; set; }
public string Farsi { get; set; }
public string Latin { get; set; }
public virtual ICollection<NEWS> NEWSs { get; set; }
}
public class UserGroup
{
public UserGroup()
{ this.Userss = new HashSet<Users>(); }
[Key]
public int UserID { get; set; }
public string Title { get; set; }
public virtual ICollection<Users> Userss { get; set; }
}
public class Users
{
public Users()
{ }
public string Name { get; set; }
public string Family { get; set; }
public string Email { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
[Key]
public int UserID { get; set; }
public virtual UserGroup UserGroup { get; set; }
// public HashSet<Users> Userss { get; set; }
}
public class NEWSDBContext : DbContext
{
public NEWSDBContext()
: base()
{
Database.SetInitializer<NEWSDBContext>(null);
}
public DbSet<NEWS> NEWSs { get; set; }
public DbSet<Users> Userss { get; set; }
public DbSet<UserGroup> UserGroups { get; set; }
public DbSet<Subjects> Subjectss { get; set; }
}
I always get an error in return View(newss.ToList());:
The underlying provider failed on Open

Multiplicity constraint violated. The role "....' of the relationship '...' has multiplicity 1 or 0..1

again i am stucked with un-clrear error raised by EF. I have the following model class:-
public partial class TMSServer
{
public TMSServer()
{
this.TMSServers1 = new HashSet<TMSServer>();
this.TMSVirtualMachines = new HashSet<TMSVirtualMachine>();
}
public int TMSServerID { get; set; }
public Nullable<int> ServerModelID { get; set; }
public int DataCenterID { get; set; }
public string ILOIP { get; set; }
public int RackID { get; set; }
public Nullable<int> StatusID { get; set; }
public Nullable<int> BackUpStatusID { get; set; }
public int RoleID { get; set; }
public Nullable<int> OperatingSystemID { get; set; }
public Nullable<int> VirtualCenterID { get; set; }
public string Comment { get; set; }
public byte[] timestamp { get; set; }
public long IT360SiteID { get; set; }
public virtual DataCenter DataCenter { get; set; }
public virtual OperatingSystem OperatingSystem { get; set; }
public virtual ServerModel ServerModel { get; set; }
public virtual Technology Technology { get; set; }
public virtual TechnologyBackUpStatu TechnologyBackUpStatu { get; set; }
public virtual TechnologyRole TechnologyRole { get; set; }
public virtual TechnologyStatu TechnologyStatu { get; set; }
public virtual TMSRack TMSRack { get; set; }
public virtual ICollection<TMSServer> TMSServers1 { get; set; }
public virtual TMSServer TMSServer1 { get; set; }
public virtual ICollection<TMSVirtualMachine> TMSVirtualMachines { get; set; }
}
}
and the following post create action method:-
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ServerJoin sj, FormCollection formValues)
{
string controllername = RouteData.Values["controller"].ToString();
if (ModelState.IsValid)
{
//code goes here
repository.InsertOrUpdateServer(sj.Server, User.Identity.Name, assetid);
repository.Save()
and the following Repository method:-
public void InsertOrUpdateServer(TMSServer server, string username,long assetid)
{
var resource = GetResourceDetials(assetid);
if (server.TMSServerID == default(int))
{
// New entity
int technologyypeID = GetTechnologyTypeID("Server");
Technology technology = new Technology
{
IsDeleted = true,
TypeID = technologyypeID,
Tag = "S" + GetTagMaximumeNumber(technologyypeID).ToString(),
StartDate = DateTime.Now,
IT360ID = assetid
};
InsertOrUpdateTechnology(technology);
Save();
var auditinfo = IntiateTechnologyAudit(tms.AuditActions.SingleOrDefault(a => a.Name.ToUpper() == "ADD").ID,
tms.TechnologyTypes.SingleOrDefault(a => a.Name.ToUpper() == "Server").AssetTypeID,
username, technology.TechnologyID);
server.TMSServerID= technology.TechnologyID;
server.IT360SiteID = resource.SITEID.Value;
tms.TMSServers.Add(server);
technology.IsDeleted = false;
InsertOrUpdateTechnology(technology);
InsertOrUpdateTechnologyAudit(auditinfo);
}
}
;
But when i try to call the Post Create action method i will get the following exception:-
System.InvalidOperationException was unhandled by user code
HResult=-2146233079 Message=Multiplicity constraint violated. The
role 'TMSServers' of the relationship 'TMSModel.FK_Servers_Technology'
has multiplicity 1 or 0..1. Source=System.Data.Entity StackTrace:
The Technology model class which is envlved in the exception looks as follow:-
public partial class Technology
{
public Technology()
{
this.TMSSwitchPorts = new HashSet<TMSSwitchPort>();
this.TechnologyAudits = new HashSet<TechnologyAudit>();
this.TechnologyIPs = new HashSet<TechnologyIP>();
}
public int TechnologyID { get; set; }
public string Tag { get; set; }
public bool IsDeleted { get; set; }
public byte[] timestamp { get; set; }
public Nullable<int> TypeID { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<long> IT360ID { get; set; }
public virtual TMSFirewall TMSFirewall { get; set; }
public virtual TMSRack TMSRack { get; set; }
public virtual TMsRouter TMsRouter { get; set; }
public virtual TMSServer TMSServer { get; set; }
public virtual TMSStorageDevice TMSStorageDevice { get; set; }
public virtual TMSSwitch TMSSwitch { get; set; }
public virtual ICollection<TMSSwitchPort> TMSSwitchPorts { get; set; }
public virtual TechnologyType TechnologyType { get; set; }
public virtual ICollection<TechnologyAudit> TechnologyAudits { get; set; }
public virtual ICollection<TechnologyIP> TechnologyIPs { get; set; }
public virtual TMSVirtualMachine TMSVirtualMachine { get; set; }
}

Categories