Linq query with group by with .NET Core - list

I'm trying to do a simple query. I want to have a list with a string and a Guid and a sub-list with a decimal and a string. I have my query this way but it keeps getting error when translated to Entity Framework what am I doing wrong?
Thanks in advance
var a = ( from c in DbContext.CC
join icc in DbContext.ICC c.Id equals icc.CCId
join i in DbContext.I on icc.IId equals i.Id
join p in DbContext.P on i.PId equals p.Id
select new
{
GuidId = p.Id,
StringN = p.StringN,
CCString = c.CCString ,
DecimalValue = icc.DecimalValue
}).GroupBy(x => new { x.GuidId , x.StringN }).
Select(x => new Model
{
GuidId = x.Key.GuidId ,
StringN = x.Key.StringN ,
Values= x.Select(y => new OtherModel
{
DecimalValue = y.DecimalValue ,
CCString = y.CCString
})
}
).OrderBy(x => x.StringN );
Error:
The LINQ expression '(GroupByShaperExpression:
KeySelector: new {
GuidId = (p.Id),
StringN = (p.Name)
},
ElementSelector:new {
GuidId = (ProjectionBindingExpression: GuidId ),
StringN = (ProjectionBindingExpression: StringN ),
CCString = (ProjectionBindingExpression: CCString ),
DecimalValue = (ProjectionBindingExpression: DecimalValue )
}
)
.Select(y => new OtherModel{
DecimalValue = y.DecimalValue ,
CCString = y.CCString
}
)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

It is SQL limitation. You cannot select grouped items, only Key and aggregation result is allowed.
Add AsEnumerable to your LINQ query to do grouping on the client side:
var a = (
from c in DbContext.CC
join icc in DbContext.ICC c.Id equals icc.CCId
join i in DbContext.I on icc.IId equals i.Id
join p in DbContext.P on i.PId equals p.Id
select new
{
GuidId = p.Id,
StringN = p.StringN,
CCString = c.CCString,
DecimalValue = icc.DecimalValue
})
.AsEnumerable()
.GroupBy(x => new { x.GuidId , x.StringN })
.Select(x => new Model
{
GuidId = x.Key.GuidId,
StringN = x.Key.StringN,
Values = x.Select(y => new OtherModel
{
DecimalValue = y.DecimalValue,
CCString = y.CCString
})
})
.OrderBy(x => x.StringN);

Related

How to update a field by itself in linq2db

I mean,
how can I translate the query
update myTable
set myField1 = myField1 + 1
where myField2 = 'xyz'
Thank you
There are several ways:
db.MyTable
.Where(x => x.MyField2 == "xyz")
.Set(x => x.MyField1, prev => prev.MyField1 + 1)
.Update();
db.MyTable
.Where(x => x.MyField2 == "xyz")
.Update(prev => new MyTable { MyField1 = prev.MyField1 + 1 });
db.MyTable
.Update(x => x.MyField2 == "xyz",
new MyTable { MyField1 = prev.MyField1 + 1 });

selectInput Category selection

I have a selectInput code as like this
selectInput('x4', 'X4', choices = list(
Eastern = c(`New York` = 'NY', `New Jersey` = 'NJ'),
Western = c(`California` = 'CA', `Washington` = 'WA')
), selectize = FALSE)
Is it possible enable section on category, like Eastern, Western. If user selected Eastern both values have to load ( New Jersey and New York). Is it possible ?
library(shiny)
onInitialize <- "
function(){
var select = this.$input[0];
this.$dropdown_content.on('mousedown', function(e){
e.preventDefault();
return false;
}).on('click', '.optgroup-header', function(e){
var options = $(this).parent().find('.option');
var items = [];
options.each(function(i, opt){items.push($(opt).data('value'));});
var selections = select.selectize.items;
select.selectize.setValue(items.concat(selections));
});
}
"
shinyApp(
ui = fluidPage(
selectizeInput("state", "Choose a state:",
list(`East Coast` = list("NY", "NJ", "CT"),
`West Coast` = list("WA", "OR", "CA"),
`Midwest` = list("MN", "WI", "IA")),
multiple = TRUE,
options = list(
onInitialize = I(onInitialize)
)
)
),
server = function(input, output){}
)

Add items to an existing list mvc5

(I am a new developer)I have a list that I put in a viewBag to make a dropwdown in my view and I would like to add 3 elements to this list so that we can see them at the end of my dropdown. I make a timesheet for the employees and I have a dropdown of the projects that the person worked during the week and I would like to add at the end of the dropdown the 3 options "Vacancy", "Unplanned Absence", "Planned Absence" if the person has been on leave instead of working.
This is my request for the projects :
var projectAssignment = (from pa in db.ProjectAssignment
join p in db.Projects on pa.ProjectId equals p.ID
where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
select new ProjectTimesheetList
{
ProjectName = p.ProjectName,
ProjectId = pa.ProjectId
});
ViewBag.ProjectTimeSHeet = projectAssignment;
This is a the modal to add my timehseet and i want to put the 3 daysoff type at the end of dropdown, so in this case after "NatureBooker"
And this is my code of my dropdown:
<select name="' + row + '_' + col + '" class="custom-select" id="tsCell_' + row + '_' + col + '" data-row="' + row + '" data-col="' + col + '">' +
'<option value="">----Select----</option>#Html.Raw(projsStr)</select>';
SOLUTION:
var projectAssignment = (from pa in db.ProjectAssignment
join p in db.Projects on pa.ProjectId equals p.ID
where pa.EmployeeId == EmployeeId && pa.StartDate !=null && (pa.EndDate == null || pa.EndDate >= DateTime.Now)
select new ProjectTimesheetList
{
ProjectName = p.ProjectName,
ProjectId = pa.ProjectId
});
List<ProjectTimesheetList> projectAssignments = projectAssignment.ToList();
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Vacancy",
ProjectId = -1,
});
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Unplanned Absence",
ProjectId = -2,
});
projectAssignments.Add(new ProjectTimesheetList
{
ProjectName = "Planned Absence",
ProjectId = -3,
});
ViewBag.ProjectTimeSHeet = projectAssignments;
And the result:
Still not clear what exactly you want, but if my guess is right you probably want to add "fake" projects to the enumerable you're binding to (not a list, by the way).
As long as you understand that this is absolutely wrong and grounds for being fired on the spot, here you go:
ViewBag.ProjectTimeSHeet = projectAssignment
.Concat(new[]
{
new ProjectTimesheetList
{
ProjectName = "Vacancy",
ProjectId = -1,
},
new ProjectTimesheetList
{
ProjectName = "Unplanned Absence",
ProjectId = -2,
},
new ProjectTimesheetList
{
ProjectName = "Planned Absence",
ProjectId = -3,
},
});
var myOptions = {
val1 : 'Vacancy',
val2 : 'Unplanned Absence',
val3 : 'Planned Absence',
};
var mySelect = $('#dropdownID');
$.each(myOptions, function(val, text) {
mySelect.append(
$('<option></option>').val(val).html(text)
);
});
through Javascript
var ddl = document.getElementById("dropdownID");
for ( let key in myOptions )
{
var option = document.createElement("OPTION");
option.innerHTML = key
option.value = myOptions[key]
ddl.options.add(option);
}

How to do a MaxBy in RavenDb MapReduce

Using the Northwind database from RavenDB tutorial I'm trying to group orders by employee and get the most resent order for every employee.
Map:
from order in docs.Orders
select new {
Employee = order.Employee,
Count = 1,
MostRecent = order.OrderedAt,
MostRecentOrderId = order.Id
}
Reduce with nonexisting MaxBy:
from result in results
group result by result.Employee into grp
select new {
Employee = grp.Key,
Count = grp.Sum(result => result.Count),
MostRecent = grp.Max(result => result.MostRecent),
MostRecentOrderId = grp.MaxBy(result => result.MostRecent).MostRecentOrderId,
}
Reduce attempt:
from result in results
group result by result.Employee into grp
let TempMostRecent = grp.Max(result => result.MostRecent)
select new {
Employee = grp.Key,
Count = grp.Sum(result => result.Count),
MostRecent = TempMostRecent,
MostRecentOrderId = grp.First(result => result.MostRecent == TempMostRecent).MostRecentOrderId
}
However my reduce attempt returns 0 results.
Also: will RavenDB treat the Order.OrderetAt as a proper DateTime value and order them correctly?
You need to do it like
from order in docs.Orders
select new {
Employee = order.Employee,
Count = 1,
MostRecent = order.OrderedAt,
MostRecentOrderId = order.Id
}
from result in results
group result by result.Employee into grp
let maxOrder = grp.OrderByDescending(x=>x.MostRecent).First()
select new {
Employee = grp.Key,
Count = grp.Sum(result => result.Count),
MostRecent = maxOrder.MostRecent,
MostRecentOrderId = maxOrder.MostRecentOrderId,
}

Add Netsuite Sales order items

I am getting this type of error:
=> i am getting error in the integration of the netsuite.
In sales order add the items in the netsuite so there are some error is define in above section my code is below please see the code add how to solve this problem.
[code] => USER_ERROR
[message] => You must enter at least one line item for this transaction.
[type] => ERRORi am gatting this type of error please help me
[code] => USER_ERROR
[message] => You must enter at least one line item for this transaction.
[type] => ERROR
my code is
include('NetSuiteService.php');
$service = new NetSuiteService();
if($order_items->netsuitid > 0){
$internal_Id = $order_items->netsuitid;
$emailCustomer = $order_items->user_email;
}
else{
$customer_Info = $order->get_customer_info($order->user_id);
$customer_information = array();
foreach($customer_Info as $customer_key => $customer_value){
if($customer_value->meta_key == 'first_name'){
$customer_information['first_name'] = $customer_value->meta_value;
}
if($customer_value->meta_key == 'last_name'){
$customer_information['last_name'] = $customer_value->meta_value;
}
}
$customer_information['email'] = $customer_Info->user_email;
//Add customer into net suit integration
$service = new NetSuiteService();
$customer = new Customer();
$customer->lastName = $customer_information['last_name'];
$customer->firstName = $customer_information['first_name'];
$customer->companyName = 'Company Name';
$customer->phone = '2222222222';
$customer->email = $customer_information['email'];
$emailCustomer = $customer_information['email'];
$request = new AddRequest();
$request->record = $customer;
$addResponse = $service->add($request);
if (!$addResponse->writeResponse->status->isSuccess) {
echo "You are already Registered with Netsuit.";
}
else {
$internal_Id = $addResponse->writeResponse->baseRef->internalId;
$order->insert_Customer($internal_Id,$order->user_id);
}
//End customer into net suit integration
}
//Add Product Information
/*$items = array();
foreach ( $order_items as $item_id => $item ) {
$itemRef = new nsRecordRef(array('internalId'=>$internal_Id));
$qty = $item['qty'];
if($item['type'] == 'line_item'){
$salesOrderItemFieldArray = array(
"item" => $itemRef,
"quantity" => $qty
);
}
if($item['type'] == 'fee'){
$salesOrderItemFieldArray = array(
"item" => $itemRef,
"quantity" => $qty
);
}
$SalesOrderItem->setFields($salesOrderItemFieldArray);
$items[] = $SalesOrderItem;
}
$salesOrderItemList = new nsComplexObject("SalesOrderItemList");
$salesOrderItemList->setFields(array(
"item" => $items
));
$salesOrderFields = array(
"orderStatus" => $order->status,
"entity" => '',
"getAuth" => true,
"shippingCost" => $order->order_shipping,
"shipMethod" => $order->payment_method,
"toBeEmailed" => true,
"email" => $emailCustomer,
"itemList" => $salesOrderItemList
);*/
$so = new SalesOrder();
//created Date
//$so->createdDate = $order->order_date;
//entity
$so->entity = new RecordRef();
$so->entity->internalId = $internal_Id;
$so->entity->name = $order->order_custom_fields['_billing_company'][0];
//Transaction Id
//$so->tranId = $order->order_custom_fields['Transaction ID'][0];
//Transaction Paid Date
//$so->tranDate = $order->order_custom_fields['_paid_date'][0];
//Source
$so->source = 'littlecrate';
//Created From
$so->createdFrom = 'littlecrate.com';
//Currency Name
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->currency = $order->order_custom_fields['_order_currency'];
$so->currencyName = $geoplugin->countryName;
$so->currency = $order->order_custom_fields['_order_currency'][0];
//Discount
$so->discountRate = $order->order_custom_fields['_order_discount'][0];
//Tax
$so->taxRate = $order->order_custom_fields['_order_tax'][0];
//email
$so->email = $order->billing_email;
//Status
//$so->orderStatus = $order->status;
//Billing Address
$so->billAddressList = array(
'billFirstname' => $order->order_custom_fields['_billing_first_name'][0],
'lastname' => $order->order_custom_fields['_billing_last_name'][0],
'billAddressee' => $order->order_custom_fields['_billing_address_1'][0],
'billAddr1' => $order->order_custom_fields['_billing_address_2'][0],
'billCountry' => $order->order_custom_fields['_billing_country'][0],
'billState' => $order->order_custom_fields['_billing_state'][0],
'billZip' => $order->order_custom_fields['_billing_postcode'][0],
'billPhone' => $order->order_custom_fields['_billing_phone'][0],
'billEmail' => $order->order_custom_fields['_billing_email'][0]);
//Shipping Address
$so->shipAddressList = array(
'shipFirstname' => $order->order_custom_fields['_shipping_first_name'][0],
'shipLastname' => $order->order_custom_fields['_shipping_last_name'][0],
'shipAddressee' => $order->order_custom_fields['_shipping_address_1'][0],
'shipAddr1' => $order->order_custom_fields['_shipping_address_2'][0],
'shipCity' => $order->order_custom_fields['_shipping_city'][0],
'shipState' => $order->order_custom_fields['_shipping_state'][0],
'shipZip' => $order->order_custom_fields['_shipping_postcode'][0],
'shiplPhone' => $order->order_custom_fields['_billing_phone'][0],
'shipEmail' => $order->order_custom_fields['_billing_email'][0]);
//Ship Date
//$so->shipDate = $order->order_custom_fields['Transaction ID'][0];
//Shipping Method
$so->shipMethod = $order->shipping_method;
//Shipping Charges
$so->shippingCost = $order->order_shipping;
//Shipping Tax Rate
$so->shippingTax1Rate = $order->order_shipping_tax;
//Payment Method
$so->paymentMethod = $order->payment_method;
//Sub Total
//$so->subTotal = $order->order_total;
//Discount Total(Cart Total)
//$so->discountTotal = $order->cart_discount;
//Tax Total
//$so->taxTotal = $order->order_tax;
//Total
//$so->total = $order->order_total;
//Product Listing
$arrItemsList = array();
$i = 0;
foreach($order_items_product as $keyProduct =>$valueProduct){
if($valueProduct['type'] == 'line_item'){
//$arrItemsList[$i]['item']['internalId'] = $valueProduct['product_id'];
//$arrItemsList[$i]['item']['externalId'] = $keyProduct;
$arrItemsList[$i]['item']['name'] = $valueProduct['name'];
$arrItemsList[$i]['item']['quantity'] = $valueProduct['qty'];
$arrItemsList[$i]['item']['description'] = $valueProduct['type'];
$arrItemsList[$i]['item']['amount'] = $valueProduct['line_total'];
}
if($valueProduct['type'] == 'fee'){
//$arrItemsList[$i]['item']['internalId'] = $valueProduct['product_id'];
//$arrItemsList[$i]['item']['externalId'] = $keyProduct;
$arrItemsList[$i]['item']['name'] = $valueProduct['name'];
$arrItemsList[$i]['item']['quantity'] = $valueProduct['qty'];
$arrItemsList[$i]['item']['description'] = $valueProduct['type'];
$arrItemsList[$i]['item']['amount'] = $valueProduct['line_total'];
}
$i++;
}
//print_r($arrItemsList);
$so->itemList->item = $arrItemsList;
/*$so->itemList = new SalesOrderItemList();
$soi = new SalesOrderItem();
$soi->item = new RecordRef();
$soi->item->internalId = 15;
$soi->quantity = 3;
$soi->price = new RecordRef();
$soi->price->internalId = $id;
$soi->amount = 55.3;
$so->itemList->item = array($soi);*/
$request = new AddRequest();
$request->record = $so;
//print_r($request);
$addResponse = $service->add($request);
print_r($addResponse);
exit;
if (!$addResponse->writeResponse->status->isSuccess) {
echo "ADD ERROR";
} else {
echo "ADD SUCCESS, id " . $addResponse->writeResponse->baseRef->internalId;
}
+
I Complited Using The Help Of Saqib,
http://stackoverflow.com/users/810555/saqib
He is The Great Developer And Regarding Netsuite Information Please Contact To Saqib Thanks Man U Just Do It.
<?php
$order_date = date('Y-m-d H:i:s');
// create array of fields
$itemArr = array();
$i = 0;
foreach($order_items_product as $keyProduct =>$valueProduct){
//if you not have internal id of item in netsuuite then please add the item in the netsuite and try.
$netsuiteItemId = 'Your Item Internal id Which is in the Netsuite Item';
$itemArr[$i]['item']['internalId'] = $netsuiteItemId;
$itemArr[$i]['quantity'] = $valueProduct['qty'];
$i++;
}
if (!define('LF', "\n")) {
define('LF', "\n");
}
/* for use in formatting custom addresses since NetSuite converts to <br> */
//Billing Address Information
/* this example has the customer address info in a db record, just pulled into $row */
$billAddress = stripslashes($order->order_custom_fields['_billing_first_name'][0]) . ' ' . $order->order_custom_fields['_billing_last_name'][0] . LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_address_1'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_address_2'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_country'][0]).LF;
$billAddress .= stripslashes($order->order_custom_fields['_billing_state'][0]) . ' - ' . $order->order_custom_fields['_billing_postcode'][0] . ', ' . LF;
$billAddress .= $order->order_custom_fields['_billing_phone'][0] . ', ' . $order->order_custom_fields['_billing_email'][0];
//Shipping Address Information
$shipAddress = stripslashes($order->order_custom_fields['_shipping_first_name'][0]) . ' ' . $order->order_custom_fields['_shipping_last_name'][0] . LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_address_1'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_address_2'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_city'][0]).LF;
$shipAddress .= stripslashes($order->order_custom_fields['_shipping_state'][0]) . ', ' . $order->order_custom_fields['_shipping_postcode'][0] . ', ' . LF;
$shipAddress .= $order->order_custom_fields['_billing_phone'][0] .', '. $order->order_custom_fields['_billing_email'][0];
$purchaseOrderFields = array (
'entity' => array ('internalId' => $internal_Id, 'type' => 'customer'),
'shippingCost' => $order->order_shipping,
'shipMethod' => $order->payment_method,
'toBeEmailed' => true,
//'tranId' => $order->order_custom_fields['Transaction ID'][0],
//'tranDate' => date('Y-m-d H:i:s'),
'source' => 'littlecrate',
'createdFrom' => 'littlecrate.com',
'discountRate' => $order->order_custom_fields['_order_discount'][0],
'taxRate' => $order->order_custom_fields['_order_tax'][0],
'email' => $order->billing_email,
//'shipDate' => date('Y-m-d H:i:s'),
'shipMethod' => $order->shipping_method,
'shippingCost' => $order->order_shipping,
'shippingTax1Rate' => $order->order_shipping_tax,
'paymentMethod' => $order->payment_method,
//'taxTotal' => $order->order_tax,
//'total' => $order->order_total,
'billAddress' => $billAddress,
'shipAddress' => $shipAddress,
'itemList' => array (
'item' => $itemArr
)
);
$salesOrder = new nsComplexObject('SalesOrder');
$salesOrder ->setFields($purchaseOrderFields);
$addResponse = $myNSclient->add($salesOrder );
if (!$addResponse->isSuccess) {
echo "Order Information is Not Inserted Into The Netsuite. Please Contact to Administration.";
exit;
}
?>
You item List object doesn't seem in correct format. Your code should look like this
$itemArr = array();
foreach($order_items_product as $keyProduct =>$valueProduct){
$item = new SalesOrderItem();
$item->item = $valueProduct['product_id'];
$item->quantity = $valueProduct['qty'];
$itemArr[] = $item;
}
$itemList = new SalesOrderItemList();
$itemList->item = $itemArr;
$so->itemList->item = $itemList;