Nested List Item reflecting type error - wpf

I have a model that contain variables and a list of another class instance..
here models:
public class patient
{
[XmlElement("firstname")]
public string name { get; set; }
[XmlElement("lastname")]
public string surname { get; set; }
[XmlElement("age")]
public int age { get; set; }
[XmlElement("gender")]
public string gender { get; set; }
[XmlArray("exams"), XmlArrayItem(typeof(exam), ElementName = "exam")]
public List<exam> exam { get; set; }
}
public class exam
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement(ElementName = "date", DataType = "DateTime")]
public DateTime date { get; set; }
[XmlElement("comment")]
public string comment { get; set; }
}
List<exam> examsLocal = new List<exam>(){
new exam{ id = "id of patient 1", date = DateTime.Now, comment = "coomment exam1" },
};
List<patient> overview = new List<patient>();
try
{
var b = new List<patient>()
{
new patient{ name = "name of patient 1", surname = "surname of patient 1", gender = "Female", age = 31, exam=examsLocal },
};
var writer = new System.Xml.Serialization.XmlSerializer(typeof(List<patient>));//throw exception
the line throws exceptions works fine if I delete 'exam=examsLocal' varible from List..
What is the correct way of serialize nested List items

Update your class definition of exam to be looks like:
remove the DataType of Date Property because the System.DateTime not allowed in Xml Serialization:
public class exam
{
[XmlElement("id")]
public string id { get; set; }
[XmlElement(ElementName = "date")]
public DateTime date { get; set; }
[XmlElement("comment")]
public string comment { get; set; }
}
And update the Property declaration in patiant class:
[XmlArray("exams"), XmlArrayItem(typeof(exam), ElementName = "exams")]
public List<exam> exams { get; set; }

Related

INSERT statement conflicted with foreign key constraint - SQL Server/Entity Framework Core

I get this error in my .NET Core 3.1 app:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_DiaryDiaryEntry". The conflict occurred in database "xxxxxx", table "dbo.Diaries", column 'Id'.
I can't see anything wrong with the tables themselves.
public partial class Diaries
{
public long Id { get; set; }
public string CoverImage { get; set; }
public short Year { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public long ChildId { get; set; }
public Children Child { get; set; }
public ICollection<DiaryEntries> DiaryEntries { get; set; }
}
public partial class DiaryEntries
{
public long Id { get; set; }
public DateTime Date { get; set; }
public string Content { get; set; }
public long DiaryId { get; set; }
public Diaries Diary { get; set; }
public ICollection<Images> Images { get; set; }
}
My code? Probably an entirely different matter.
This is the code that generates the error.
[HttpPost("CreateYear/{id}")]
public async Task<IActionResult> CreateYearOfEntries([FromRoute] int id)
{
// The id is the ID of an existing diary
// Make sure the diary does exist first and that it belongs to the current logged-in user
var diary = _diaryRepository.Find(id);
if (diary == null) return NotFound();
var year = diary.Result.Year;
if (await _diaryEntryRepository.OwnerIsLoggedIn(LoggedInUser.ParentId, id))
{
var noOfDays = DateTime.IsLeapYear(year) ? 366 : 365;
var i = 0;
for (; i < noOfDays; i++)
{
var date = new DateTime(year, 1, 1).AddDays(i);
var newDiaryEntry = new DiaryEntries()
{
Content = " ",
Date = date,
DiaryId = diary.Id
};
await _diaryEntryRepository.Add(newDiaryEntry);
}
return Ok();
}
return NotFound();
}
public class DiaryEntryRepository : IDiaryEntryRepository
{
private readonly ApplicationDbContext _context;
public DiaryEntryRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<DiaryEntries> Add(DiaryEntries diaryEntry)
{
await _context.DiaryEntries.AddAsync(diaryEntry);
await _context.SaveChangesAsync();
return diaryEntry;
}
}

Invalid column name exception thrown in .NET Core web api

I have two classes in my database which are defined as classes, fed into entity and then called from the API
The full method is below for the calls. The first call works fine, the second throws the exception
public async Task<ActionResult<List<QuizForms>>> GetQuiz([FromQuery]string id)
{
var form = await _context.QuizForms.Where(t=>t.QuizId == id).ToListAsync();
if (form == null)
{
return NotFound();
}
var elem = new List<Element>();
foreach(var e in form)
{
var data = await _context.Element.Where(t => t.ElementId == e.ElementId).ToListAsync();
elem.AddRange(data);
e.Element.AddRange(elem);
}
return form;
}
When the var data line is hit, an excception is thrown
Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'QuizFormsFormId'.
It looks like the name of the class and column name are being concatenated and the used as the query parameter.
The two classes look like this
public class QuizForms
{
[Key]
public int FormId { get; set; }
public string QuizId { get; set; } = "";
#nullable enable
public string? Title { get; set; }
public int? ElementId { get; set; }
public List<Element>? Element { get; set; }
public int? PreviousId { get; set; }
public int? NextId { get; set; }
#nullable disable
}
and
public class Element
{
[Key]
public int Id { get; set; }
public int ElementId { get; set; }
#nullable enable
public int? MathsId { get; set; }
public int? QuestionId { get; set; }
public int? InformationId { get; set; }
public int? AnswerId { get; set; }
#nullable disable
public string QuizId { get; set; } = "";
}
Is it because I'm not using Id for the primary key or do I need to do something else so the class and property aren't concatented like this?

how to display data from both two tables in database in a View in mvc4 razor

Can anybody guide me how to display data from two tables in database in view page of MVC4 using razor?i googled it but i didnt find answer for this
LeadDetail.cs
public partial class LeadDetail
{
public int LeadID { get; set; }
public string LeadName { get; set; }
public virtual logintable logintable { get; set; }
}
EmployeDetail.cs
public partial class EmployeDetail
{
public int EmployeID { get; set; }
public int UserID { get; set; }
public string EmployeeName { get; set; }
public virtual logintable logintable { get; set; }
}
Parentview.cs in viewmodels folder
public class Parentview
{
public List<LeadDetail> LeadDetails { get; set; }
public List<EmployeDetail> EmployeDetails { get; set; }
public ParentsInformationViewModel(List<LeadDetail> _LeadDetails, List<EmployeDetail> _EmployeDetails) //Should i pass all the required parameters that i want to display in view ????
{
LeadDetails = _LeadDetails;
EmployeDetails = _EmployeDetails;
}
Homecontroller.cs
public ActionResult view()
{
List<LeadDetail> LeadObj = new List<LeadDetail> ();
List<EmployeDetail> EmployeObj = new List<EmployeDetail> ();
// get list of parents here
Parentview ParentInfoVMObj = new Parentview();
ParentInfoVMObj.LeadDetails = LeadObj;
ParentInfoVMObj.EmployeDetails = EmployeObj;
return View(ParentInfoVMObj);
}
see below sample
First Table
public class Table1
{
public int Id{ get; set; }
public string Name{ get; set; }
}
Second Table
public class Table2
{
public int Id{ get; set; }
public string Name{ get; set; }
}
ViewModel
public class ViewModelForTwoTables
{
public List<Table1> table1Data { get; set; }
public List<Table2> table2Data { get; set; }
}
see below example
public ActionResult TeamStat()
{
var players = db.Players().ToList();
var seasons = db.Seasons().ToList();
var view = new TeamStat()
{
Players = players,
Seasons = seasons
};
return View(view);
}
in view
#foreach (var player in Model.Players) { ....
#foreach (var player in Model.Seasons) { ....

The Insert statement conflict with the FOREIGN KEY constraint. Entity Framework

my models are as follows...
public class Company
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
[MaxLength(255)]
public string Fullname { get; set; }
public bool HasFuneralInsuranceParlours { get; set; }
public bool HasFuneralInsurancePolicies { get; set; }
public bool HasLifeInsurancePolicies { get; set; }
public bool IsDeleted { get; set; }
public virtual List<Office> Offices { get; set; }
}
public class Office
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(100)]
public string Address1 { get; set; }
[MaxLength(100)]
public string Address2 { get; set; }
[MaxLength(100)]
public string Address3 { get; set; }
[MaxLength(20)]
public string Telephone { get; set; }
[MaxLength(20)]
public string Fax { get; set; }
[MaxLength(255)]
public string Email { get; set; }
public bool IsDeleted { get; set; }
public Guid CompanyId { get; set; }
public virtual Company Companies { get; set; }
public virtual List<Employee> Employees { get; set; }
}
and controllers
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(OfficeModel model)
{
bool success = false;
string message = "";
byte[] logo = null;
var user = SecurityHelper.GetAuthenticatedUser(this.HttpContext);
try
{
if (ModelState.IsValid)
{
if (model.Name.IsNullOrWhitespace()) throw new Exception("Unable to create this Employee Name. The Type cannot be blank or spaces.");
if (models.Offices.Any(x => x.Name.ToLower() == model.Name.ToLower())) throw new Exception(string.Format("This Office's Name '{0}' already exists. Please check your data.", model.Name.ToUpperCase()));
var entry = new Office
{
Id = Guid.NewGuid(),
Name = model.Name.ToUpperCase(),
Address1 = model.Address1.ToUpperCase(),
Address2 = model.Address2.ToUpperCase(),
Address3 = model.Address3.ToUpperCase(),
Telephone = model.Telephone.ToUpperCase(),
Fax = model.Fax.ToUpperCase(),
Email = model.Email.ToUpperCase(),
IsDeleted = false,
CompanyId = user.CompanyId,
Bankings = new List<Banking>()
{
new Banking
{
Bank = model.OfficeBank.ToUpperCase(),
Account = model.BankAccount.ToUpperCase(),
Branch = model.Branch.ToUpperCase(),
BranchNo = model.BranchNo.ToUpperCase(),
AccountType = model.AccountType.ToUpperCase()
}
}
};
models.Offices.Add(entity);
success = true;
return RedirectToAction("Index");
}
else
{
message = "An error was cought please check your data and retry";
}
}
catch (Exception ex)
{
message = ex.Message;
}
return View(model);
}
when l debug the above code l return the following error
"The INSERT statement conflicted with the FOREIGN KEY constraint
\"FK_dbo.Offices_dbo.Companies_CompanyId\". The conflict occurred in
database \"PolicyManager\", table \"dbo.Companies\", column
'Id'.\r\nThe statement has been terminated."
When l hover model.Name l am return a value but the rest return me a null value which l suspect the thus the cause of the the above error.
What problem can it possible be because l have used the similar code before and it worked. May anyone help. Thank you in advance
You are adding a New Office.
The error says that there is a referential integrity problem With the Foreign key constraint to the Company table.
When you create the Order you add the following Company key:
CompanyId = user.CompanyId
So it appears that user.CompanyId is not an id that is registered against an existing Company.

Classes and relationship design in mvc 3.0

I have currently have the following classes:
public class Ticket
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public int ClientId { get; set; }
public virtual Client Client { get; set; }
public virtual ICollection<Item> Items { get; set; }
public Ticket()
{
Items = new List<Item>();
}
}
public class Client
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
public class Item
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public double Price { get; set; }
public virtual ICollection<Ticket> Tickets { get; set; }
}
My Problem/Question is the following, let's say I create a new Item: "Item1" and set its price to "3.00", I add that Item to a few "Tickets", i.e., "Ticket1": "Item1", "3.00"; "Ticket2": "Item1", "3.00", etc. If after adding these items to the tickets I change "Item1"'s price to "4.00" it would change the price of the ticket I already created, how can I have it change the price for only ticket created after the price change?
This is my ticket controller:
[HttpPost]
public ActionResult Create(TicketViewModel ticketViewModel)
{
if (ModelState.IsValid)
{
var ticket = new Ticket();
ticket = ticketViewModel.Ticket;
AddOrUpdateItems(ticket, ticketViewModel.Item);
context.Tickets.Add(ticket);
context.SaveChanges();
return RedirectToAction("Index");
}
return View(ticketViewModel);
}
private void AddOrUpdateItems(Ticket ticket, ICollection<AssignedItem> assignedItems)
{
foreach (var assignedItem in assignedItems)
{
if (assignedItem.Assigned)
{
var item = context.Items.Find(assignedItem.ItemId);
ticket.Items.Add(item);
}
}
}

Resources