How to avoid Dupliate value in View - asp.net

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();

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

Could not get the data from IQueryable<object>

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

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

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

how to assign value to entity got from database

I have a linq query like below:
public IQueryable<vmEmp> GetEmp(int crewid)
{
var dt = new EmpEntities();
var e = from t in dt.tblEmp
where (t.CrewId == crewid)
select new vmEmp
{
Id = -1,
Crew = t.crewid,
Name = t.Name,
Address = t.Address
};
return e;
}
I hope can make the Id auto decrease by 1 till end of the employee.
like first's Id is -1, second's is -2, third is -3 ...
How to do that here? Thanks a lot
If this was LINQ-to-objects, you could use this overload of Select:
var dt = new EmpEntities();
var e = dt.tblEmp
.Where(t => t.CrewId == crewid)
.Select((t,index) => new vmEmp
{
Id = -index - 1,
Crew = t.crewid,
Name = t.Name,
Address = t.Address
});
But EF doesn't suport this, because the indexer can't be translated into SQL. So you need a work-around:
var dt = new EmpEntities();
var e = dt.tblEmp
.Where(t => t.CrewId == crewid)
.Select(t => new
{
Id = 0,
Crew = t.crewid,
Name = t.Name,
Address = t.Address
}
.AsEnumerable() // Continue in memory
.Select((t,index) => new vmEmp
{
Id = -index - 1,
Crew = t.Crew,
Name = t.Name,
Address = t.Address
});
Side note: it's recommended to put dt in a using construct.
Use a counter variable and decrease it for every record while you project it to your custom POCO.
public IQueryable<vmEmp> GetEmp(int crewid)
{
int counter=0;
var dt = new EmpEntities();
//load the items to a list of anonymous type
var eList = from t in dt.tblEmp
where (t.CrewId == crewid)
.Select(s=>
new { Id = 0,
Crew = s.crewid,
Name = s.Name,
Address = s.Address
}).ToList();
var e=eList.Select(x=> new vmEmp
{
Id = --counter,
Crew = x.Crew,
Name = x.Name,
Address = x.Address
});
return e.AsQueryable();
}

Resources