could not translate expression into sql - c#

With the below code I get this error
InvalidOperationException:
Could not translate expression
stok_getmiktar_byyapilanislem(urunler.ID,
"SATIS") into SQL and could not treat
it as a local expression.
var urundb = (from urunler in db.TBLP1URUNs
orderby urunler.SERIAL
where (urunler.ID.Contains(FilitreText) || urunler.URUNADI.Contains(FilitreText))
&& ((kategori1.SERIAL == null) || urunler.SERIAL.StartsWith(kategori1.SERIAL))
select new
{
UrunNo = urunler.ID,
UrunAdi = urunler.URUNADI,
Marka = urunler.MARKA,
SatisFiyati = urunler.SATFIYAT1.GetValueOrDefault(0),//.ToString() + " " + urunler.SATFIYAT1BIRIM,
TedarikFiyati = urunler.TEDFIYAT1.GetValueOrDefault(0),//.ToString() + " " + urunler.TEDFIYAT1BIRIM,
PiyasaFiyati = urunler.SATFIYAT2.GetValueOrDefault(0),//.ToString() + " " + urunler.SATFIYAT2BIRIM,
Hizmet = (urunler.HIZMETYENSURYIL > 0 && urunler.HIZMETYENSURAY > 0 ?
urunler.HIZMETYENSURYIL.ToString() + " Yıl " + urunler.HIZMETYENSURAY.ToString() + " Ay"
: (urunler.HIZMETYENSURYIL > 0 && urunler.HIZMETYENSURAY <= 0 ?
urunler.HIZMETYENSURYIL.ToString() + " Yıl"
: (urunler.HIZMETYENSURYIL <= 0 && urunler.HIZMETYENSURAY > 0 ?
urunler.HIZMETYENSURAY.ToString() + " Ay"
: ""))),
TedarikEdilenMiktar = DAOUrun.stok_getmiktar_byyapilanislem(urunler.ID, "TEDARIK"),//this one works fine
SatilanMiktar = DAOUrun.stok_getmiktar_byyapilanislem(urunler.ID, "SATIS"),//this one works fine
Stok = urunler.TEDARIKCISTOKMIKTAR.GetValueOrDefault(0)
- DAOUrun.stok_getmiktar_byyapilanislem(urunler.ID, "SATIS")//error occurs with this one
});
below is stok_getmiktar_byyapilanislem
public static double stok_getmiktar_byyapilanislem(string urun_id, string yapilanislem)
{
VeriyazDBDataContext db = new VeriyazDBDataContext(); db.Connection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString;
double miktar = (from rows in db.TBLP1ISLEMDETAYs
where rows.URUN_ID == urun_id && rows.TBLP1ISLEM.YAPILANISLEM == yapilanislem
select rows.MIKTAR).Sum().GetValueOrDefault(0);
return miktar;
}
How can I solve it?

For those who are or who may be confronted with and suffered from this error
check Custom Method in LINQ to SQL query and Calling functions in LINQ queries
they say we cannot call our own functions/methods in linq, actually we can but when trying to get something from that query it throws the referred exception in my question.What I really wonder is why this one
SatilanMiktar = DAOUrun.stok_getmiktar_byyapilanislem(urunler.ID, "SATIS"),
works but this one doesn't
Stok = urunler.TEDARIKCISTOKMIKTAR.GetValueOrDefault(0) - DAOUrun.stok_getmiktar_byyapilanislem(urunler.ID, "SATIS")
I just wrote some other method like this:
public static double GetMevcutMiktar(string urunId,double acilisMiktari)
{
double mevcutMiktar = 0;
mevcutMiktar = acilisMiktari - stok_getmiktar_byyapilanislem(urunId, "SATIS")
return mevcutMiktar;
}
And called it instead of
urunler.TEDARIKCISTOKMIKTAR.GetValueOrDefault(0) - DAOUrun.stok_getmiktar_byyapilanislem(urunler.ID, "SATIS")

Related

how to get more than 5000 entities by using Factories GetByFilter method with prestasharp

Library Version:
1.2.9
NuGet Package Url:
https://www.nuget.org/packages/PrestaSharp/1.2.9
Prestashop version:
1.7.7.0
Describe the Bug:
PrestaSharp GetByFilter with pagination always return same entity list
Since ProductFactory's GetByFilter method returns null if there are more than 5000 products that match the filter. I decide to get them by pagination like this
_productFactory.GetIdsByFilter(filter, null, "[" + startingIndex.ToString() + "," + count.ToString() + "]");
but even if startingIndex(because of a loop) changes the result is the same
Full code:
filter.Add("date_upd", "[" + dFrom + "," + dTo + "]");
int i = 0;
List<long> AllProducts = new List<long>();
List<long> products;
while (true) // this loop never breaks
{
int startingIndex = i++ * count;
products = _productFactory.GetIdsByFilter(filter, null, "[" + startingIndex.ToString() + "," + (count).ToString() + "]"); // returns same products in every iteration
if (products?.Any() == true) // to check the list is not empty
{
AllProducts.AddRange(products);
if (products.Count < count)
{
break;
}
}
else
break;
}
You just have to remove the brackets from the 'limit' parameter. It is an error in the Github documentation when they give the example with brackets. Here's an own implementation where I send multiple requests in parallel to speed up the processing, regards.
public async Task<List<PS_Entity>> GetElements(int pageSize = 100) {
try {
var numberOfElements = factory.GetIds().Count;
var numberOfParallelTasks = numberOfElements >= pageSize ? numberOfElements / pageSize : 1;
var loadElementsTasks = Enumerable.Range(0, numberOfParallelTasks).Select(taskNumber => factory.GetByFilterAsync(null, "id_ASC", $"{taskNumber * pageSize},{pageSize}")).ToList();
if (numberOfElements % pageSize != 0) {
var skiped = numberOfParallelTasks * pageSize;
loadElementsTasks.Add(factory.GetByFilterAsync(null, "id_ASC", $"{skiped},{numberOfElements - skiped}"));
}
var elements = (await Task.WhenAll(loadElementsTasks)).SelectMany(elements => elements).ToList();
return elements;
} catch (PrestaSharpException e) {
if ((int)e.ResponseHttpStatusCode == 404)
Console.WriteLine($"No existen {RemoveFactoryFromName(factory)}'s.");
return new List<PS_Entity>();
}
}

Populating data from database into multiple colums equally?

I'm trying to populate two different container equally with data coming from the database. Putting 5 locations in the first container and 6 at the second. Every time that run this code, it populates all into the left container.
Any Ideas what am I missing?
shopDataContext dc = new shopDataContext();
var areas = (from s in dc.Areas select s);
String content = "";
foreach(var a in areas) {
if (a.id >= 1 && a.id <= 6) {
content += "<div><h3>" + a.Tittle + "</h3>";
var aStores = (from s in dc.Stores where s.areaid == a.id select s);
foreach(var s in aStores) {
content += "<p>" + s.Tittle + "</p>";
}
leftContent.InnerHtml = leftContent.InnerHtml + content;
} else {
content += "<div><h3>" + a.Tittle + "</h3>";
var aStores = (from s in dc.Stores where s.areaid == a.id select s);
foreach(var s in aStores) {
content += "<p>" + s.Tittle + "</p>";
}
rightContent.InnerHtml = rightContent.InnerHtml + content;
}
}
I guess you want to reset the added content in each iteration of the loop:
...
foreach(var a in areas) {
string content = "";
if (a.id >= 1 && a.id <= 6) {
...
}
}
....
Otherwise the content is added several times.

Error Using Decimal And Bool

In my syntax below I get an error of
An exception of type 'System.FormatException' occured in mscorlib.dll but was not handled in ther user code
Additional Information: Input string was not in a correct format
And the value being passed that throws the error is 9.7000
And this is my syntax - I have a comment above the line that throws an error
private void calculate()
{
var qtys = val(dropdownlist.SelectedItem.Text) + "|" + val(dropdownlist1.SelectedItem.Text) + "|" + val(dropdownlist2.SelectedItem.Text) ;
var totalitems = dropdownitem.SelectedItem.Text + "|" + dropdownitem1.SelectedItem.Text + "|" + dropdownitem2.SelectedItem.Text + "|" + dropdownitem3.SelectedItem.Text;
var amounts = dropdownamt.SelectedItem.Value + "|" + dropdownamt1.SelectedItem.Value + "|" + dropdownamt2.SelectedItem.Value + "|" + dropdownamt3.SelectedItem.Value;
var totalitems = itemInfo.Split('|');
var qtys = qty.Split('|');
var amounts = amount.Split('|');
for (int i = 0; i < totalitems.Count(); i++)
{
if (totalitems[i] != "" && qtys[i] != "" && qtys[i] != "0")
{
TotalPrice += Math.Round(val(amounts[i]), 2);
TotalTax += Math.Round(val(amounts[i]) * Convert.ToDecimal(0.07), 2);
}
}
}
private decimal val(string p)
{
if (p == null)
return 0;
else if (p == "")
return 0;
//The value of p = 9.7000
return Convert.ToInt16(p);
}
You're trying to return a decimal but calling Convert.ToInt16 try Convert.ToDecimal
Also I would recommend using decimal.TryParse rather than calling Convert directly with some code like this:
public decimal convert(string p)
{
decimal result;
if(decimal.TryParse(p, out result))
return result;
else
return 0;
}

TreeNode.Add() doesn't show any response

i have a class that starts with a variable of type TreeNode in System.Windows.Forms. The class's functions job is to add some nodes to this variable .. but the problem is when i try to add some nodes to it the debugger freeze up and doesn't show any response .. I searched over the internet but i didn't find such a problem .This is one of those functions
NOTE : the line that produce issue is commented
public Node Factor()
{
Node result = new Node();
if (count < tokens.Count && tokens[count] == TokenType.LeftParentheses)
{
this.Match(TokenType.LeftParentheses);
result = this.Expression();
if (!this.Match(TokenType.RightParentheses))
return null;
result.viewnode.Text = "Expression";
}
else if (tokens[count] == TokenType.Num)
{
if (!this.Match(TokenType.Num))
return null;
NumberNode nnode = new NumberNode(lexemes[count - 1]);
nnode.childs = "NumberNode : Value " + nnode.value + '\n';
nnode.viewnode = new TreeNode("Number - Value = " + nnode.value);
result = nnode;
result.viewnode = nnode.viewnode;
result.viewnode.Nodes.Add(nnode.viewnode);
}
else
{
if (!this.Match(TokenType.ID))
return null;
IdNode inode = new IdNode(lexemes[count - 1], "0");
inode.childs = "IdNode - Value : " + inode.name + '\n';
inode.viewnode = new TreeNode("Id - " + inode.name);
result = inode;
result.viewnode = inode.viewnode;
//the program freezes at this line
inode.viewnode.Nodes.Add(inode.viewnode);
}
return result;
}
You are adding the node to itself.
should be result.viewnode ...

Search between two dates not working

I have the following code:
var q = context.Fuels.AsQueryable();
if (dateEdit1.EditValue != null && dateEdit2.EditValue != null)
{
q.Where(d => d.FuelDate >= dateEdit1.DateTime && d.FuelDate <= dateEdit2.DateTime);
}
and it's working, it will get all rows in table.
but when I'm using this code:
if (dateEdit1.EditValue != null && dateEdit2.EditValue != null)
{
var r = context.ExecuteStoreQuery<Fuel>(String.Format("SELECT * FROM Fuel WHERE FuelDate BETWEEN '{0}' AND '{1}'",
dateEdit1.DateTime.Year + "-" + dateEdit1.DateTime.Month + "-" + dateEdit1.DateTime.Day,
dateEdit2.DateTime.Year + "-" + dateEdit2.DateTime.Month + "-" + dateEdit2.DateTime.Day));
}
it's working but I need to use the first way to get relations working.
Any idea what is the problem in the first one?
Inside of your if clause, you need to assign it to q, if you don't do that q is just a query for all Fuels
This should work:
q = q.Where(d => d.FuelDate >= dateEdit1.DateTime && d.FuelDate <= dateEdit2.DateTime);

Categories

Resources