Could not get the data from IQueryable<object> - asp.net

I have this in my server to fetch data from a database:
[HttpPost]
[Route("api/getaddress")]
public IQueryable<PreAddress> GetAddress()
{
var httpRequest = HttpContext.Current.Request;
var id = httpRequest["personId"];
int personId;
if (!Int32.TryParse(id, out personId)) return null;
using (var db = new ApplicationDbContext())
{
var preAddress = (from pa in db.PersonAndAddresses
join a in db.Addresses on pa.AddressId equals a.AddressId
join b in db.PersonBarangays on a.BarangayCode equals b.BarangayCode
join m in db.PersonMunicipals on a.MunicipalCode equals m.MunicipalCode
join p in db.PersonProvinces on a.ProvinceCode equals p.ProvinceCode
join r in db.PersonRegions on a.RegionCode equals r.RegionCode
where pa.PersonId == personId
select new PreAddress()
{
BarangayCode = b.BarangayName,
AddressId = a.AddressId,
HouseNumber = a.HouseNumber,
MunicipalCode = m.MunicipalName,
ProvinceCode = p.ProvinceName,
RegionCode = r.Region,
StreetName = a.StreetName,
UnitNumber = a.UnitNumber,
VillageSubdivision = a.VillageSubdivision
});
return preAddress;
}
}
This is how I get the data from the client:
service
getAddress() {
const endpoint = this.rootUrl + '/api/getaddress';
const formData: FormData = new FormData();
formData.append('personId', this.genParams.personId);
return this.http.post(endpoint, formData);
}
component
getPersonInformation() {
this.clientService.getPerson(this.genParams.personId)
.subscribe((data: any) => {
console.log(data);
this.person = data;
});
}
Following the server using debugger, I can actually get a value but in my client side. I get the following error:
I need your help. Thank you.

Try updating your code like this:
[HttpPost]
[Route("api/getaddress")]
public PreAddress GetAddress()
{
var httpRequest = HttpContext.Current.Request;
var id = httpRequest["personId"];
int personId;
if (!Int32.TryParse(id, out personId)) return null;
PreAddress preAddress;
using (var db = new ApplicationDbContext())
{
var preAddress = (from pa in db.PersonAndAddresses
join a in db.Addresses on pa.AddressId equals a.AddressId
join b in db.PersonBarangays on a.BarangayCode equals b.BarangayCode
join m in db.PersonMunicipals on a.MunicipalCode equals m.MunicipalCode
join p in db.PersonProvinces on a.ProvinceCode equals p.ProvinceCode
join r in db.PersonRegions on a.RegionCode equals r.RegionCode
where pa.PersonId == personId
select new PreAddress()
{
BarangayCode = b.BarangayName,
AddressId = a.AddressId,
HouseNumber = a.HouseNumber,
MunicipalCode = m.MunicipalName,
ProvinceCode = p.ProvinceName,
RegionCode = r.Region,
StreetName = a.StreetName,
UnitNumber = a.UnitNumber,
VillageSubdivision = a.VillageSubdivision
});
preAddress = preAddress.FirstOrDefault();
}
return preAddress;
}

You need to execute the IQuerable before you return it, in this scenario try with ToList()
[HttpPost]
[Route("api/getaddress")]
public IEnuerable<PreAddress> GetAddress()
{
var httpRequest = HttpContext.Current.Request;
var id = httpRequest["personId"];
int personId;
if (!Int32.TryParse(id, out personId)) return null;
using (var db = new ApplicationDbContext())
{
var preAddress = (from pa in db.PersonAndAddresses
join a in db.Addresses on pa.AddressId equals a.AddressId
join b in db.PersonBarangays on a.BarangayCode equals b.BarangayCode
join m in db.PersonMunicipals on a.MunicipalCode equals m.MunicipalCode
join p in db.PersonProvinces on a.ProvinceCode equals p.ProvinceCode
join r in db.PersonRegions on a.RegionCode equals r.RegionCode
where pa.PersonId == personId
select new PreAddress()
{
BarangayCode = b.BarangayName,
AddressId = a.AddressId,
HouseNumber = a.HouseNumber,
MunicipalCode = m.MunicipalName,
ProvinceCode = p.ProvinceName,
RegionCode = r.Region,
StreetName = a.StreetName,
UnitNumber = a.UnitNumber,
VillageSubdivision = a.VillageSubdivision
});
return preAddress.ToList(); //invoke it here
}
}

Related

how to Add list of products from cart?

dears,
i have an API working with ASP.Net Core 3.1 posting orders
i want to post order head and get all items from another api in cart items and post it in order items my code as below
[HttpPost("addOrderHead")]
public async Task<ActionResult<OrderDto>> Posting(OrderDto dto)
{
try
{
if (dto == null)
{
return BadRequest(ModelState);
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var mappedEntities = _mapper.Map<Order>(dto);
_orderRepository.Add(mappedEntities);
if (await _orderRepository.Save())
{
int id = mappedEntities.OrderID;
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
var cartDto = new CartItemDto();
foreach(var item in cartItems)
{
cartDto.ItemID = item.ItemID;
cartDto.ItemLookupCode = item.ItemLookupCode;
cartDto.CategoryID = item.CategoryID;
cartDto.DepartmentID = item.DepartmentID;
cartDto.itemDescription = item.itemDescription;
cartDto.SubDescription3 = item.SubDescription3;
cartDto.Quantity = item.Quantity;
cartDto.Weight = item.Weight;
cartDto.SnapShotPrice = item.SnapShotPrice;
cartDto.StoreId = item.StoreId;
cartDto.barcode = item.barcode;
cartDto.Email = item.Email;
cartDto.ItemImage = item.ItemImage;
};
var items = new OrderItems()
{
OrderId = id,
ItemID = cartDto.ItemID,
ItemLookupCode = cartDto.ItemLookupCode,
CategoryID = cartDto.CategoryID,
DepartmentID = cartDto.DepartmentID,
itemDescription = cartDto.itemDescription,
SubDescription3 = cartDto.SubDescription3,
Quantity = cartDto.Quantity,
Weight = cartDto.Weight,
SnapShotPrice = cartDto.SnapShotPrice,
StoreId = cartDto.StoreId,
barcode = cartDto.barcode,
Email = cartDto.Email,
ItemImage = cartDto.ItemImage,
};
_orderItemsRepository.Add(items);
await _orderItemsRepository.Save();
return Ok(id);
}
return BadRequest(ModelState);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, ex.InnerException.Message);
}
}
every time i run this api order header added successfully and order items add first item only
which cart items return with array of items ,
can any one help me in that ,
You need to put Add (and maybe .Save()) inside the foreach:
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
foreach(var item in cartItems)
{
var cartDto = new CartItemDto(); // inside foreach
cartDto.ItemID = item.ItemID;
....
var item = new OrderItems() // one item - not: items
{
OrderId = id,
ItemID = cartDto.ItemID,
...
ItemImage = cartDto.ItemImage,
};
_orderItemsRepository.Add(item); // add item before moving to next item.
}
await _orderItemsRepository.Save();
BTW. I'm not sure why you need cartDto; I think you can eliminate it:
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
foreach(var item in cartItems)
{
var item = new OrderItems() // one item - not: items
{
OrderId = id,
ItemID = item.ItemID,
...
ItemImage = item.ItemImage,
};
_orderItemsRepository.Add(item); // add item before moving to next item.
}
await _orderItemsRepository.Save();
The code is not correct.In the below line you it should be List instead of object
var cartItems = await _cartItemRepository.GetCartItems(mappedEntities.ApplicationUserId);
var cartDtoList = new List<CartItemDto>();
foreach(var item in cartItems)
{
carDto carDto= new CarDto();
cartDto.ItemID = item.ItemID;
cartDto.ItemLookupCode = item.ItemLookupCode;
cartDto.CategoryID = item.CategoryID;
cartDto.DepartmentID = item.DepartmentID;
cartDto.itemDescription = item.itemDescription;
cartDto.SubDescription3 = item.SubDescription3;
cartDto.Quantity = item.Quantity;
cartDto.Weight = item.Weight;
cartDto.SnapShotPrice = item.SnapShotPrice;
cartDto.StoreId = item.StoreId;
cartDto.barcode = item.barcode;
cartDto.Email = item.Email;
cartDto.ItemImage = item.ItemImage;
carDtoList.Add(carDto)
};
Similarly the orderItems will also be list.
The other simplest solution is to put all the things inside foreach loop like this
foreach(var item in cartItems)
{
cartDto.ItemID = item.ItemID;
cartDto.ItemLookupCode = item.ItemLookupCode;
cartDto.CategoryID = item.CategoryID;
cartDto.DepartmentID = item.DepartmentID;
cartDto.itemDescription = item.itemDescription;
cartDto.SubDescription3 = item.SubDescription3;
cartDto.Quantity = item.Quantity;
cartDto.Weight = item.Weight;
cartDto.SnapShotPrice = item.SnapShotPrice;
cartDto.StoreId = item.StoreId;
cartDto.barcode = item.barcode;
cartDto.Email = item.Email;
cartDto.ItemImage = item.ItemImage;
var items = new OrderItems()
{
OrderId = id,
ItemID = cartDto.ItemID,
ItemLookupCode = cartDto.ItemLookupCode,
CategoryID = cartDto.CategoryID,
DepartmentID = cartDto.DepartmentID,
itemDescription = cartDto.itemDescription,
SubDescription3 = cartDto.SubDescription3,
Quantity = cartDto.Quantity,
Weight = cartDto.Weight,
SnapShotPrice = cartDto.SnapShotPrice,
StoreId = cartDto.StoreId,
barcode = cartDto.barcode,
Email = cartDto.Email,
ItemImage = cartDto.ItemImage,
};
_orderItemsRepository.Add(items);
await _orderItemsRepository.Save();
return Ok(id);
}

How to avoid Dupliate value in View

I have a ProductList with Product of different categorises.
I dont want my view to hold duplicate values.
ProductController.cs
public ActionResult ProductList()
{
IEnumerable<ProductListDTO> ProductList;
if (User.IsInRole("Admin"))
{
ProductList = from a in _db.ProductMsts
join b in _db.ProductTypeMsts on a.fk_prodtypeid equals b.pk_prodtypeid
select new ProductListDTO
{
pk_ProductId = a.pk_ProductId,
ProductType = b.Description,
ProductName = a.ProductName,
OriginalPrice = a.OriginalPrice,
ProductQuantity = a.ProductQuantity,
SellingUptoPrice = a.SellingUptoPrice
};
}
else
{
ProductList = from a in _db.ProductMsts
join b in _db.ProductTypeMsts on a.fk_prodtypeid equals b.pk_prodtypeid
where a.username==User.Identity.Name
select new ProductListDTO
{
pk_ProductId = a.pk_ProductId,
ProductType = b.Description,
ProductName = a.ProductName,
OriginalPrice = a.OriginalPrice,
ProductQuantity = a.ProductQuantity,
SellingUptoPrice = a.SellingUptoPrice
};
}
return View(ProductList);
You can use distinct() with the query syntax you have used.
ProductList = from a in _db.ProductMsts
join b in _db.ProductTypeMsts on a.fk_prodtypeid equals b.pk_prodtypeid
select new ProductListDTO
{
pk_ProductId = a.pk_ProductId,
ProductType = b.Description,
ProductName = a.ProductName,
OriginalPrice = a.OriginalPrice,
ProductQuantity = a.ProductQuantity,
SellingUptoPrice = a.SellingUptoPrice
}.Distinct();

how to solve error like "Cannot implicitly convert type"?

Code:
public IEnumerable<InvoiceStringData> GetInvoiceByID(string orderID)
{
var orderId = Convert.ToInt32(orderID);
ResponseDetails jsonRes = new ResponseDetails();
List<string> campaignidByProdid = new List<string>();
Productlevelcharges prodlevel = new Productlevelcharges();
List<Productlevelcharges> lstprodlevel = new
List<Productlevelcharges>();
List<OrderVM> lstorvm = new List<OrderVM>();
List<ProductMaster> lstpmvm = new List<ProductMaster>();
List<OrderDetailsVM> lstodvm = new List<OrderDetailsVM>();
List<ProductVariant> lstpvvm = new List<ProductVariant>();
List<CampaignProductMapper> lstcmvm = new
List<CampaignProductMapper>();
List<CampaignVm> lstcm = new List<CampaignVm>();
List<InvoiceStringData> Bill = new List<InvoiceStringData>();
InvoiceStringData InvoiceStringData = new InvoiceStringData();
var orderChargId = _context.Orderlevelcharges.Where(a => a.OrderId == orderId).Select(a => a.OrderChargeId).FirstOrDefault();
var orderCharge = orderChargId.ToString();
var lst = CalculateUnitPrice(orderCharge, orderID);
var result = (from v in lst
group v by new
{
v.InvoiceDate,
v.InvoiceNo,
v.NetAmount,
v.TotalAmount,
v.SaveAmount
} into order
select new
{
invoiceDate = order.Key.InvoiceDate,
netAmount = order.Key.NetAmount,
totalAmount = order.Key.TotalAmount,
saveAmount = order.Key.SaveAmount,
// productMasterlst=order
_invoice = new
{
product = order.Select(o => new {
o.productName, o.UnitPrice, o.Quantity, o.UnitOfMeasure, o.hsnCode,
o.Weight, o.Tax1Sgst, o.Tax2Cgst, o.Tax3Igst })
}
}).ToList();
return result;
}
error:
CS0266 Cannot implicitly convert type
'System.Collections.Generic.List<> product> _invoice>>' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) Payment.API D:\Consumer Billing\MRU 15-05-18 10.47\MRU Current\src\Services\Payment\Payment.API\BAL\Repository\InvoiceRepo.cs 131 Active

Join two dynamic Linq in Asp.net

I have used linq to store data, below is the code:
var result = (dynamic)null;
var serviceData = (dynamic)null;
var userData = (dynamic)null;
/****Linq 1*****/
serviceData= dtPasscode.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
/**Linq 2**/
userData = DisplyCustomerDetails(Convert.ToInt64(strSubAccountID));
result = serviceData.Concat(userData);
And another linq through function:
/**Function**/
System.Data.EnumerableRowCollection DisplyCustomerDetails(Int64 intAccountId)
{
var result = (dynamic)null;
/** Data Display if no service avaiable **/
IAccount_BL objAccount_BL = new Account_BL();
Customer objCustomer = new Customer();
DataTable dtCustomer = null;
int intErrorCount = 0;
objCustomer.Account_Id = Convert.ToInt64(intAccountId);
dtCustomer = objAccount_BL.GetCustomerDetails(objCustomer, ref intErrorCount);
objAccount_BL = null;
objCustomer = null;
if (intErrorCount == 0)
{
if (dtCustomer != null)
{
if (dtCustomer.Rows.Count > 0)
{
result = dtCustomer.AsEnumerable().Select(m => new
{
ACCOUNT_ID = intAccountId,
SUB_ACC_ID = m.Field<string>("ACCOUNT_ID_ALIAS")
});
}
}
}
return result;
}
I wanted to join both the result of Linq1 & Linq2, I tired Concat & Union, getting below error
'System.Data.EnumerableRowCollection<<>f__AnonymousTypea>' does not contain a definition for 'Concat'
To Concat both enumerables must of the same class; you cannot use anonymous classes. Define a class that has the two fields and change the code to Select them.
Also, don't use ... = (dynamic) null; just assign the variable directly
var serviceData= dtPasscode ...
var userData = DisplyCustomerDetails ...
var result = serviceData.Concat(userData);

is there a way to get rid of DTO

I am using Entity Framework. I have the following query in which I get data using two tables Application and Employee connected by a foreign key EmployeeID in Application Table. The tables have 1-1 relationship .
Is there a way to simplify the following code and get rid of the DTO Employee1
which is the same as auto generated Employee class
public List<Employee1> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = (from a in context.Applications
join e in context.Employees on a.EmployeeID equals e.EmployeeID
where
(
a.ApplicationID == ApplicationID
)
select new Employee1
{
EmployeeID = e.EmployeeID,
SecondEmail = e.SecondEmail,
EmailID = e.EmailID,
Title = e.Title,
Name = e.Name,
Rank = e.Rank,
POBox = e.POBox,
Phone = e.Phone,
JoinDate = e.JoinDate,
Status = e.Status,
DepartmentID = e.DepartmentID.Value,
NameString = e.NameString,
Department = e.Department,
ParentDept = e.ParentDept,
DepartmentAr = e.DepartmentAr,
NameAr = e.NameAr,
NameStringAr = e.NameStringAr,
TitleAr = e.TitleAr
}).ToList();
return data;
}
If you need to return list of Employees, just select e which refers to Employee and don't use Employee1 as a DTO.
public List<Employee> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = (from a in context.Applications
join e in context.Employees on a.EmployeeID equals e.EmployeeID
where
(
a.ApplicationID == ApplicationID
)
select e).ToList();
return data;
}
Another way is this, which I would prefer because of readability:
public List<Employee> GetApplicant(int ApplicationID)
{
var context = new FPSDB_newEntities();
var data = context.Applications.Where(p=>p.ApplicationID == ApplicationID).Select(p=>p.Employee).ToList();
return data;
}

Resources