Invalid column name exception thrown in .NET Core web api - sql-server

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?

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;
}
}

How to access foreign key values on MVC view?

I'm having trouble accessing foreign key values in my view without using a partial.
I have tblProperty as Primary_Key and tblCustomer as foreign_key. I want to access the values of my foreign keys in my view but can't figure out why.
Model
public partial class tblProperty
{
public tblProperty()
{
this.Images = new HashSet<Image>();
this.tblCustomers = new HashSet<tblCustomer>();
}
public int propertyID { get; set; }
public string address { get; set; }
public string description { get; set; }
public virtual ICollection<Image> Images { get; set; }
public virtual ICollection<tblCustomer> tblCustomers { get; set; }
}
public partial class tblCustomer
{
public int customerID { get; set; }
public string name { get; set; }
public decimal contactNumber { get; set; }
public string notes { get; set; }
public Nullable<int> propertyID { get; set; }
public virtual tblProperty tblProperty { get; set; }
}
controller
public class propertyController : Controller
{
propertyDBEntities2 dc = new propertyDBEntities2();
public ActionResult List()
{
var properties = dc.tblProperties.Include(p => p.tblCustomers);
return View(properties.ToList());
}
public ActionResult Details(int id = 0)
{
var properties = dc.tblProperties.Include(p => p.tblCustomers);
tblProperty property = dc.tblProperties.Find(id);
tblCustomer customer = dc.tblCustomers.Find(id);
if (properties == null)
{
return HttpNotFound();
}
return View(dc.tblProperties.Find(id));
}
public ActionResult Create()
{
return View();
}
[HttpPost, ValidateAntiForgeryToken]
public ActionResult Create(tblProperty e)
{
if (ModelState.IsValid)
{
using (dc)
{
dc.tblProperties.Add(e);
dc.SaveChanges();
}
}
return RedirectToAction("List");
}
view
(like model.name is trying to access name from tblCustomer)
#model myProject.tblProperty
#Html.DisplayFor(model => model.name)
tblProperty doesnt have name.
I guess you need
#Html.DisplayFor(model => model.tblCustomer.name)
But just debug it or use intellisense
EDIT:
In my project I create a dtoClass Data Transfer Object
So for my avl class I have a dtoAvl
avl Class:
public partial class avl
{
public avl()
{
this.cars = new HashSet<cars>();
}
public long avl_id { get; set; }
public Nullable<long> car_id { get; set; }
public Nullable<decimal> speed { get; set; }
// this class contain info regarding the road
public virtual manila_rto manila_rto { get; set; }
public virtual ICollection<cars> cars { get; set; }
}
I create a dtoAvl
public class dtoAvl
{
public long Avl_ID { get; set; }
public long? Car_ID { get; set; }
public string RoadName { get; set; } // came from manila_rto
public int Speed { get; set; }
}
My controler
List<dtoAvl> result = db.avls.Select(
r => new dtoAvl
{
Avl_ID = r.Avl_ID,
Car_ID = r.Car_ID,
Speed = r.Speed,
// here is a propery but can be a list
RoadName = r.manila_rto.name
}).ToList();
return PartialView(result);
View:
#model IEnumerable<dtoAvl>

A circular reference was detected while serializing an object of type in AngularJs and asp.net mvc

Well I know it is well known error. There are lots of questions asked here. But after going through few questions I am not able to solve my problem I am getting this error my website.
This is my error
A circular reference was detected while serializing an object of type
My Controller Code is
[HttpGet]
public JsonResult Get(int currentPage, int recordsPerPage)
{
var pageNumber = currentPage;
var pageSize = recordsPerPage;
var begin = (pageNumber - 1) * pageSize;
var totalNumberOfRecords = db.Products.Count();
var productlist = db.Products.OrderBy(r => r.ProductID).Skip(begin).Take(pageSize).ToList();
db.Configuration.ProxyCreationEnabled = false;
//var productlist = db.Products.ToList();
var product = new { Product = productlist, TotalRecords = totalNumberOfRecords };
return Json(new { Products = productlist, RecordCount = totalNumberOfRecords }, JsonRequestBehavior.AllowGet);
}
My Angular Controller Code is this
function GetProducts() {
var productResult = productService.getProduct($scope.currentPage, $scope.recordsPerPage);
productResult.then(function (result) {
console.log("d",data);
if (result.data != '' || result.data != null) {
if (result.data != null || result.data != '') {
$scope.Products = result.data;
}
else if (result.data = 0) {
$scope.message = "No Product Found"
}
}
});
};
And Angular Service code is this
this.getProduct = function (currentPage, recordsPerPage) {
return $http.get('/Home/Get?currentPage=' + currentPage + '&recordsPerPage=' + recordsPerPage);
// return $http.get('/Home/Get');
};
I am missing something but I am unable to get that. Any expert please help me in this.. I spend my whole night with this error. I try every solution of stackoverflow which I read but nothing works for me
Here is My Model
namespace StylesStore.Models
{
using System;
using System.Collections.Generic;
public partial class Product
{
public Product()
{
this.Carts = new HashSet<Cart>();
this.OrdersDetails = new HashSet<OrdersDetail>();
}
public int ProductID { get; set; }
public Nullable<int> SKU { get; set; }
public Nullable<int> VendorProductID { get; set; }
public string ProductName { get; set; }
public string ProductDescription { get; set; }
public Nullable<int> SupplierID { get; set; }
public Nullable<int> CategoryID { get; set; }
public Nullable<int> QuantityPerUnit { get; set; }
public decimal UnitPrice { get; set; }
public Nullable<int> MSRP { get; set; }
public Nullable<int> AvailableSize { get; set; }
public string AvailableColor { get; set; }
public Nullable<int> Size { get; set; }
public string Color { get; set; }
public Nullable<int> Discount { get; set; }
public Nullable<int> UnitWeight { get; set; }
public Nullable<int> UnitsInStock { get; set; }
public string UnitsInOrder { get; set; }
public string Picture1 { get; set; }
public string Picture2 { get; set; }
public string Picture3 { get; set; }
public string Picture4 { get; set; }
public Nullable<decimal> ShippingCharges { get; set; }
public string Note { get; set; }
public Nullable<bool> InStock { get; set; }
public Nullable<int> CatID { get; set; }
public Nullable<decimal> wieght { get; set; }
public Nullable<int> totalview { get; set; }
public Nullable<int> Disable { get; set; }
public Nullable<System.DateTime> EntryDate { get; set; }
public virtual ICollection<Cart> Carts { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<OrdersDetail> OrdersDetails { get; set; }
public virtual Supplier Supplier { get; set; }
}
}
You should not serialize your entity objects. Your entity objects have virtual navigation properties which are detected by JsonSerializer. JsonSerializer thinks they are embedded properties of that object and tries to serialize them too. and this goes on. serializer finds itself trying to serialize all database. this is why your error occurs.
You should either mark fields that need to be serialized or use DTO's to serialize objects.
Note: you can use AutoMapper to map objects between Entity and DTO

Exception with Foreign Key in MVC project

I'm trying to record a new entry on a table (HistoryRequestResponse), which one of the values is a foreign key to another table (HistoryRequests). I know for sure that the foreign key value (lets say 1090) exists on HistoryRequests, but when i permorm the db.SaveChanges() I get the following error:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK__HistoryRe__idReq__04AFB25B". The conflict occurred in database
"iDesk", table "dbo.HistoryRequests", column 'id'. The statement has
been terminated.
public partial class HistoryRequestResponse
{
public int id { get; set; }
public int idReq { get; set; }
public string submitUser { get; set; }
public string respType { get; set; }
public string description { get; set; }
public System.DateTime submitDate { get; set; }
public virtual ResponseType ResponseType { get; set; }
public virtual HistoryRequests HistoryRequests { get; set; }
}
public partial class HistoryRequests
{
public HistoryRequests()
{
this.HistoryRequestResponse = new HashSet<HistoryRequestResponse>();
}
public int id { get; set; }
public System.DateTime submitDate { get; set; }
public string title { get; set; }
public string description { get; set; }
public Nullable<System.DateTime> closeDate { get; set; }
public string priority { get; set; }
public string submitUser { get; set; }
public string responsible { get; set; }
public Nullable<int> serialNumber { get; set; }
public Nullable<int> area { get; set; }
public virtual Area Area1 { get; set; }
public virtual Computers Computers { get; set; }
public virtual ICollection<HistoryRequestResponse> HistoryRequestResponse { get; set; }
public virtual Priorities Priorities { get; set; }
}
Then I do the following in the POST method:
[HttpPost]
public ActionResult Reopen(int? id, string resp)
{
HistoryRequests request = db.HistoryRequests.Find(id);
try
{
var response = new HistoryRequestResponse()
{
respType = "Reabrir",
//HistoryRequests = request,
id = 0,
submitDate = DateTime.Now,
submitUser = User.Identity.Name,
description = resp
};
response.idReq = (int)id;
request.closeDate = null;
request.responsible = User.Identity.Name;
if (ModelState.IsValid)
{
db.HistoryRequestResponse.Add(response);
db.SaveChanges(); //WHERE I GET THE EXCEPTION
db.Entry(request).State = EntityState.Modified;
db.SaveChanges();
var email = from u in db.Users
where u.UserName.Equals(request.submitUser)
select u.Email;
//SmtpServer.SendEmail(email.SingleOrDefault(), requests.title, desc);
}
return RedirectToAction("Dashboard", "BHome");
}
catch (Exception e)
{
return Content("Erro ao reabrir o pedido");
}
}

Web ApI Entity Framework (Code First) Value not appearing in database

My database will run correctly, and I can input the data manually via SQL Server, however, when I try and pass the value in via my API (testing using Postman), the value won't pass into the database, it appears as "NULL".
I have a reports and a bookings tables.
This is the code for the reports:
public class Report
{
public Report()
{
Injuries = new List<Injury>();
this.Bookings = new HashSet<Booking>();
}
public int Id { get; set; }
public string Club1 { get; set; }
public string Club2 { get; set; }
public virtual ICollection<Injury> Injuries { get; set; }
public virtual ICollection<Booking> Bookings { get; set; }
}
Bookings:
public class Booking
{
//public Booking()
//{
// Reports = new List<Report>();
//}
public int Id { get; set; }
public string Club { get; set; }
public string PlayerName { get; set; }
public string PlayerNumber { get; set; }
public string Reason { get; set; }
public string Description { get; set; }
//public int? Report_Id { get; set; }
public Nullable<int> Report_Id { get; set; }
public virtual Report Report { get; set; }
//public virtual ICollection<Report> Reports { get; set; }
}
Controller:
//POST: api/Reports
[ResponseType(typeof(Report))]
public async Task<IHttpActionResult> PostReport(Report report)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Reports.Add(report);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = report.Id }, report);
}
I put the test information via Postman:
I'm not sure why Report_Id is showing as it's not required, however, Report_Id1 is the field that is connecting the Report and Booking together.
Since your foreign key doesn't follow convention (ReportId), you need to use the annotation [ForeignKey] or a fluent api configuration:
modelBuilder.Entity<Booking>()
.HasRequired(b => b.Report)
.WithMany(b => b.Bookings)
.HasForeignKey(p => p.Report_Id);
That is why EF is adding the second Report_ID1. https://msdn.microsoft.com/en-us/data/hh134698.aspx

Resources