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

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

Related

Angularjs WebApi is not working in Asp.net MVC Entity Framework

This error is Occur after running the web application. this is picture of inspect elements of google chrome.
See Image
See Second Image
i want to us entity framework
here is class code... when i comment the
public virtual List tblproduct { get; set; } and
public virtual List tblproduct { get; set; } this its working perfetcly how to completety use entity framework mvc in it
[Table("tblCatagory")]
public class AddCatagory
{
public int Id { get; set; }
[StringLength(56)]
public string CataName { get; set; }
public virtual List<Product> tblproduct { get; set; }
//public virtual List<AddSubCatagory> tblsubcatagory { get; set; }
}
[Table("tblSubCatagory")]
public class AddSubCatagory
{
public int Id { get; set; }
[StringLength(56)]
public string SubCataName { get; set; }
public int AddCatagoryId { get; set; }
public virtual AddCatagory tblcatagory { get; set; }
public virtual List<Product> tblproduct { get; set; }
}
product class code
[Table("tblProduct")]
public class Product
{
public int Id { get; set; }
[StringLength(56)]
public string ProductName { get; set; }
[StringLength(156)]
public string ProductDes { get; set; }
public int ProductQty { get; set; }
public double ProductRate { get; set; }
public double Inches { get; set; }
public DateTime Date { get; set; }
public int AddCatagoryId { get; set; }
public int AddSubCatagoryId { get; set; }
public virtual AddCatagory tblcatagory{ get; set; }
public virtual AddSubCatagory tblsubcatagory{ get; set; }
}
wepapi controller
public List<Product> Getproducts()
{
var result = db.products.ToList();
return result;
}
angularjs code..
GetAllPro();
function GetAllPro() {
$http.get("/api/Products").then(function (response) {
$scope.Pro = response.data;
}, function () {
alert("Error")
})
}

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>

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

Entity Framework: Unable to determine the principal end of the relationship. Multiple added entities may have the same primary key

I'm getting this error while updating the model I'm sharing my code, please tell me the best solution for this.
Ticket Detail Class:
public class TicketDetail
{
[Key]
public int TicketDetailId { get; set; }
public int GenericOrderId { get; set; }
public int PartId { get; set; }
public int Quantity { get; set; }
public decimal? CustomerPrice { get; set; }
public string Status { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public virtual Part Part { get; set; }
public virtual Ticket Ticket { get; set; }
}
OrderDetailClass:
public class OrderDetail
{
[Key]
public int OrderDetailId { get; set; }
public int GenericOrderId { get; set; }
public int PartId { get; set; }
public int Quantity { get; set; }
public decimal? UnitPrice { get; set; }
public string Status { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
public virtual Part Part { get; set; }
public virtual Order Order { get; set; }
}
Order Class:
public class Order : GenericOrder
{
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
Ticket Class
public class Ticket : GenericOrder
{
public virtual ICollection<TicketDetail> TicketDetails { get; set; }
}
GenericOrderClass:
public abstract class GenericOrder
{
[Key]
public int GenericOrderId { get; set; }
public string ProcessId { get; set; }
public DateTime Date { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Company { get; set; }
public string Phone { get; set; }
public string Message { get; set; }
public decimal Total { get; set; }
[Timestamp]
public byte[] RowVersion { get; set; }
}
and this is the controller class code
TryUpdateModel(order);
TryUpdateModel(ticket);
try
{
order.Date = DateTime.Now;
ticket.Date = DateTime.Now;
order.ProcessId = DateTime.Now.Ticks.ToString().Substring(12, 6);
ticket.ProcessId = order.ProcessId;
//Add the Order
storeDB.Orders.Add(order);
storeDB.Tickets.Add(ticket);
//Process the order
cart.CreateOrder(order);
cart.CreateTicket(ticket);
// Save all changes
storeDB.SaveChanges();
//return RedirectToAction("Complete",
// new { id = order.QuoteOrderId });
TempData["OrderSuccess"] = "Your order has been submitted successfully with the Process ID " + order.ProcessId;
TempData["OrderId"] = order.GenericOrderId;
TempData["Email"] = order.Email;
return RedirectToAction("Confirm");
}
catch (Exception e)
{
//Invalid - redisplay with errors
ModelState.AddModelError("", e.Message);
return View(order);
}
I have searched internet but couldn't find any solution.
Try saving Order and Ticket and after they are saved add Details to them.

Breeze saving strategy

I'm creating my first spa with angular and breeze. So for so good and i'm very happy with the progress I've made. But now I'm stuck on my editing and saving my entity product (example class below). When I edit a product i also call the related products, and I have a checkbox (on saving) that says "override related products with same info". But what is the best way to do this? Server side? Should i expand the model on the client side? Are there examples available?
Product:
public class Product
{
#region Fields
private ICollection<ProductCategory> _productCategories;
private ICollection<ProductManufacturer> _productManufacturers;
private ICollection<ProductPicture> _productPictures;
private ICollection<ProductSpecificationAttribute> _productSpecificationAttributes;
private ICollection<ProductTierPrice> _productTierPrices;
#endregion Fields
#region Properties
public int Id { get; set; }
public ProductType ProductType { get; set; }
public int ParentGroupedProductId { get; set; }
public bool VisibleIndividually { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string MetaTitle { get; set; }
public string MetaDescription { get; set; }
public int DisplayOrder { get; set; }
public bool LimitedToStores { get; set; }
public string Sku { get; set; }
public string UniqueCode { get; set; }
public decimal Price { get; set; }
public decimal OldPrice { get; set; }
public decimal? SpecialPrice { get; set; }
public DateTime? SpecialPriceStartDateTimeUtc { get; set; }
public DateTime? SpecialPriceEndDateTimeUtc { get; set; }
public decimal DiscountPercentage { get; set; }
public bool HasTierPrices { get; set; }
public TaxRate TaxRate { get; set; }
public bool SyncToShop { get; set; }
public bool Deleted { get; set; }
public bool Locked { get; set; }
public State State { get; set; }
public DateTime? DateChanged { get; set; }
public DateTime? DateCreated { get; set; }
#endregion Properties
#region Mapping
public virtual ICollection<ProductCategory> ProductCategories
{
get { return _productCategories ?? (_productCategories = new List<ProductCategory>()); }
protected set { _productCategories = value; }
}
public virtual ICollection<ProductManufacturer> ProductManufacturers
{
get { return _productManufacturers ?? (_productManufacturers = new List<ProductManufacturer>()); }
protected set { _productManufacturers = value; }
}
public virtual ICollection<ProductPicture> ProductPictures
{
get { return _productPictures ?? (_productPictures = new List<ProductPicture>()); }
protected set { _productPictures = value; }
}
public virtual ICollection<ProductSpecificationAttribute> ProductSpecificationAttributes
{
get { return _productSpecificationAttributes ?? (_productSpecificationAttributes = new List<ProductSpecificationAttribute>()); }
protected set { _productSpecificationAttributes = value; }
}
public virtual ICollection<ProductTierPrice> ProductTierPrices
{
get { return _productTierPrices ?? (_productTierPrices = new List<ProductTierPrice>()); }
protected set { _productTierPrices = value; }
}
#endregion Mapping
}
Related Product:
public class RelatedProduct
{
#region Fields
#endregion Fields
#region Properties
public int Id { get; set; }
public int ProductId1 { get; set; }
public int ProductId2 { get; set; }
public int DisplayOrder { get; set; }
public State State { get; set; }
#endregion Properties
//#region Mapping
//public virtual Product Product1 { get; set; }
//public virtual Product Product2 { get; set; }
//#endregion Mapping
}
Capture Changes of All Products in Clinent Jquery Array and send to Server Side..
Serverside change your controller method argument to IEnumerable products , so you can save all changes in Batch
If you want to update only change value use HttpPatch on server side and update changed value only

Resources