I'm trying to make a progress bar for my SQL query but don't know where to start. I have tried implementing the backgroundworker but I can't seem to get it to work.
I'm using VS 2010 .NET 4.0
Treinen trein = listboxVoertuigNr.SelectedItem as Treinen;
List<string> treinenIds = new List<string>();
foreach (var item in listboxVoertuigNr.SelectedItems)
{
treinenIds.Add(item.ToString());
}
fouten = eventsEntities.Foutens;
category = eventsEntities.Category_MMAP;
IEnumerable<dynamic> FoutenResultaat = new List<dynamic>();
FoutenResultaat =
(from x in treinen
join fout in fouten
on x.TreinId equals fout.TreinId
where dateStart <= fout.Datum && dateEnd >= fout.Datum
&& treinenIds.Contains(fout.Treinen.Name)
&& fout.Omschrijving.Contains(textboxFilterOmschrijving.Text)
&& fout.FoutCode.Contains(textboxFilterFout.Text)
&& fout.Module.Contains(textboxFilterModule.Text)
orderby fout.Datum descending, fout.Time descending
join cat in category
on fout.FoutCode equals cat.Foutcode
select new
{
Datum = fout.Datum,
Time = fout.Time,
FoutCode = fout.FoutCode,
Omschrijving = fout.Omschrijving,
Module = fout.Module.ToUpper(),
FoutId = fout.FoutId,
Name = x.Name,
Category = cat.Cat_MMAP
});
GetGraad(FoutenResultaat);
In GetGraad() the read data from the SQL database gets placed in a list. This is a custom list because it also gets populated with values from a excel file.
private void GetGraad(IEnumerable<dynamic> mijnResultaten)
{
foreach (dynamic item in mijnResultaten)
{
string graad = "";
string Toolbox = "";
if (item.Module.Contains("_"))
modNaam = item.Module.Split('_');
else if (item.Module.Contains(" "))
modNaam = item.Module.Split(' ');
string compare = modNaam[0].Substring(0, modNaam[0].Length - 1).ToString();
if (compare == "MPU")
{
var index = Properties.Settings.Default.listFoutcodeMPU.FindIndex(a => a == item.FoutCode);
if (index == -1)
graad = "";
else
{
graad = Properties.Settings.Default.listGraadMPU[index];
Toolbox = Properties.Settings.Default.listToolboxMPU[index];
}
}
if (compare == "AAUX")
{
var index = Properties.Settings.Default.listFoutcodeAAUX.FindIndex(a => a == item.FoutCode);
if (index == -1)
graad = "";
else
{
Toolbox = Properties.Settings.Default.listToolboxAAUX[index];
graad = Properties.Settings.Default.listGraadAAUX[index];
}
}
if (compare == "CTRL")
{
var index = Properties.Settings.Default.listFoutcodeCTRL.FindIndex(a => a == item.FoutCode);
if (index == -1)
graad = "";
else
{
Toolbox = Properties.Settings.Default.listToolboxACTRL[index];
graad = Properties.Settings.Default.listGraadCTRL[index];
}
}
string cat = Convert.ToString(item.Category);
if (cat == null)
cat = "Onbeschikbaar";
try
{
dataTreinFouten.Add(new FoutenMetNaam { Datum = item.Datum, FoutCode = item.FoutCode, Module = modNaam[0].ToUpper(), File = modNaam[1].ToUpper(), Name = item.Name, Omschrijving = item.Omschrijving, Time = item.Time, Graad = graad, FoutId = item.FoutId, Toolbox = Toolbox, Category = cat.ToUpper()});
}
catch (Exception ex)
{
Xceed.Wpf.Toolkit.MessageBox.Show(ex.Message);
}
}
}
The list is used to populate a datagrid, the class used for the list "dataTreinFouten":
class FoutenMetNaam
{
public DateTime Datum { get; set; }
public TimeSpan Time { get; set; }
public String FoutCode { get; set; }
public String Omschrijving { get; set; }
public String Module { get; set; }
public String Name { get; set; }
public int FoutId { get; set; }
public string Graad { get; set; }
public string File { get; set; }
public List<ExtraInfo> listInfoRondFout { get; set; }
public bool isManueel { get; set; }
public string Toolbox { get; set; }
public string Category { get; set; }
}
But I can't really get the state of how far the query is already. Which means I can't update a progress bar with it current state and because the database can contain over 30.000.000 results it is quite needed.
EDIT:
I added a Entity Data Model generated from my SQL database "Events".
Code to use this:
private EventsEntities eventsEntities = new EventsEntities();
Any help or pointing in the right direction is greatly appreciated!
Related
I am still having real performance issue in a list there our 38 thousand entrys and I need to map them to another table for export I am thinking of moving it to stored proc but still worried what performance would be like there. The code works but takes a very long time to execute and wish to turn it into a stored proc.
private List<TradeItemsExport> MapTradeItems(List<TradeItems> tradeItem)
{
List<TradeItemsExport> retList = new List<TradeItemsExport>();
try
{
var StockImport = new StockItemExported();
List<StandardLookUpList> _AnalsisCodes = GetAnayalsisCodesForExportCode();
StandardLookUpList sport = new StandardLookUpList();
StandardLookUpList gender = new StandardLookUpList();
StandardLookUpList colour = new StandardLookUpList();
StandardLookUpList Size = new StandardLookUpList();
StandardLookUpList categorycode = new StandardLookUpList();
StandardLookUpList categorydesc = new StandardLookUpList();
StandardLookUpList subcategorycode = new StandardLookUpList();
StandardLookUpList subcategorydesc = new StandardLookUpList();
StandardLookUpList brandcode = new StandardLookUpList();
StandardLookUpList branddesc = new StandardLookUpList();
using (var db = new liveEntities1())
{
int count = 0;
foreach (var item in tradeItem)
{
count++;
bool hasprocessed = HasTransactionBeenProcessed(item.ItemCode);
if (hasprocessed == false)
{
var codesForThisItem = _AnalsisCodes.Where(w => w.ItemCode == item.ItemCode);
if (codesForThisItem.Any())
{
sport = codesForThisItem.FirstOrDefault(x => x.code == Constants.Sport);
gender = codesForThisItem.FirstOrDefault(x => x.code == Constants.Gender);
colour = codesForThisItem.FirstOrDefault(x => x.code == Constants.Colour);
Size = codesForThisItem.FirstOrDefault(x => x.code == Constants.Size);
categorycode = codesForThisItem.FirstOrDefault(x => x.code == Constants.Category);
categorydesc = codesForThisItem.FirstOrDefault(x => x.code == Constants.Category);
subcategorycode = codesForThisItem.FirstOrDefault(x => x.code == Constants.SubCategory);
subcategorydesc = codesForThisItem.FirstOrDefault(x => x.code == Constants.SubCategory);
brandcode = codesForThisItem.FirstOrDefault(x => x.code == Constants.Brand);
string SportCodeValue, SportDescValue;
if (sport == null)
{
SportCodeValue = "";
SportDescValue = "";
}
else
{
SportCodeValue = sport.LookupValue.ToString();
SportDescValue = sport.description;
}
string GenderCodeValue, GenderCodeDesc;
if (gender == null)
{
GenderCodeValue = "";
GenderCodeDesc = "";
}
else
{
GenderCodeValue = gender.LookupValue.ToString();
GenderCodeDesc = gender.description;
}
string ColourCodeValue, ColourCodeDesc;
if (colour == null)
{
ColourCodeValue = "";
ColourCodeDesc = "";
}
else
{
ColourCodeValue = colour.LookupValue.ToString();
ColourCodeDesc = colour.description;
}
string SizeCodeValue, SizeCodeDesc;
if (Size == null)
{
SizeCodeValue = "";
SizeCodeDesc = "";
}
else
{
SizeCodeValue = Size.LookupValue.ToString();
SizeCodeDesc = Size.description;
}
string CategoryCodeValue, CategoryCodeDesc;
if (categorycode == null)
{
CategoryCodeValue = "";
CategoryCodeDesc = "";
}
else
{
CategoryCodeValue = categorycode.LookupValue.ToString();
CategoryCodeDesc = categorydesc.description;
}
string subcategorycodevalue, subcategorycodedesc;
if (categorycode == null)
{
subcategorycodevalue = "";
subcategorycodedesc = "";
}
else
{
subcategorycodevalue = subcategorycode.LookupValue.ToString();
subcategorycodedesc = subcategorydesc.description;
}
string brandcodecodevalue, brandcodecodedesc;
if (brandcode == null)
{
brandcodecodevalue = "";
brandcodecodedesc = "";
}
else
{
brandcodecodevalue = brandcode.LookupValue.ToString();
brandcodecodedesc = brandcode.description;
}
retList.Add(new TradeItemsExport()
{
ItemCode = item.ItemCode,
BarCode = item.BarCode,
Description = item.Description,
SupplierCode = item.SupplierCode,
SupplierStockCode = item.SupplierStockCode,
Product_Group_Code = "",
Product_Group_Desc = "",
SportCode = SportCodeValue,
SportDesc = SportDescValue,
GenderCode = GenderCodeValue,
GenderDesc = GenderCodeDesc,
ColourCode = ColourCodeValue,
ColourDesc = ColourCodeDesc,
SizeCode = SizeCodeValue,
SizeDesc = SizeCodeDesc,
CategoryCode = CategoryCodeValue,
CategoryDesc = CategoryCodeDesc,
subcategorycode = subcategorycodevalue,
subcategorydesc = subcategorycodedesc,
BrandsCode = brandcodecodevalue,
BrandsDesc = brandcodecodedesc,
Vat = item.Vat,
GrossWeight = item.Weight,
CommodityCode = item.CommodityCode,
price_exVAT = item.price_exVAT,
price_incVAT = item.price_incVAT,
currentprice_exVAT = item.currentprice_exVAT,
currentprice_incVAT = item.currentprice_incVAT,
creation_date = item.creation_date,
Inactive_date = item.Inactive_date,
status = 1
});
Console.Write(String.Format("Exporting stock item {0} with a current record of {1} of {2} \n", item.ItemCode.ToString(), count.ToString(), tradeItem.Count.ToString()));
EFStockItemExported _newStockitemImported = new EFStockItemExported();
_newStockitemImported.StockItemID = item.ItemCode;
_newStockitemImported.IsProcessed = true;
_newStockitemImported.DateImported = DateTime.Now;
db.EFStockItemExporteds.Add(_newStockitemImported);
db.SaveChanges();
}
else
{
Console.Write(string.Format("Stock Items to Process [{0}] check the table and remove entry if wish to re process.", 0));
}
}
}
}
}
catch (Exception ex)
{
}
return retList;
}
My problem that this takes around 30 mins to compute the results which is very slow.
This is the sql that I am doing which is a view that is the tradeitem that I am passing.
SELECT
dbo.PLSupplierAccount.SupplierAccountNumber, dbo.PLSupplierAccount.PLSupplierAccountID, dbo.PLSupplierAccount.SupplierAccountName,
dbo.PLSupplierAccount.SYSCurrencyID, dbo.PLSupplierAccount.MainTelephoneAreaCode, dbo.PLSupplierAccount.MainTelephoneCountryCode,
dbo.PLSupplierAccount.MainTelephoneSubscriberNumber, dbo.PLSupplierAccount.MainFaxCountryCode, dbo.PLSupplierAccount.MainFaxSubscriberNumber,
dbo.PLSupplierAccount.MainFaxAreaCode, dbo.PLSupplierContact.ContactName, dbo.PLSupplierContact.Description, dbo.PLSupplierContact.FirstName,
dbo.PLSupplierContact.MiddleName, dbo.PLSupplierContact.LastName, loc.AddressLine1, loc.AddressLine2, loc.AddressLine3, loc.AddressLine4, loc.PostCode,
loc.City, loc.County,
CAST(CASE WHEN loc.Country = 'Ireland' THEN 'IRL'
WHEN loc.Country = 'Great Britain'
THEN 'GBR'
ELSE 'ERR'
END AS nvarchar(3)) AS Country,
dbo.SYSCurrency.SYSCurrencyISOCodeID, dbo.SYSCurrency.SYSExchangeRateTypeID, dbo.SYSCurrency.Name AS CurrencyDescription,
dbo.SYSCurrency.Symbol AS CurrencySymbol
FROM
dbo.PLSupplierAccount
INNER JOIN
dbo.PLSupplierContact ON dbo.PLSupplierAccount.PLSupplierAccountID = dbo.PLSupplierContact.PLSupplierAccountID
INNER JOIN
dbo.PLSupplierLocation AS loc ON dbo.PLSupplierAccount.PLSupplierAccountID = loc.PLSupplierAccountID
AND dbo.PLSupplierContact.PLSupplierLocationID = loc.PLSupplierLocationID
INNER JOIN
dbo.SYSCurrency ON dbo.PLSupplierAccount.SYSCurrencyID = dbo.SYSCurrency.SYSCurrencyID
My quesiton is how would I change the above to include a sub query that would do the same as this function is doing above.
The query for the codes look up which is again another view is below.
SELECT
dbo.StockItem.ItemID, dbo.StockItem.Code, dbo.StockItem.Name, dbo.StockItemSearchCatVal.SearchValueID, dbo.SearchValue.Name AS Expr1,
dbo.SearchCategory.Name AS Expr2
FROM
dbo.SearchCategory
INNER JOIN
dbo.SearchValue ON dbo.SearchCategory.SearchCategoryID = dbo.SearchValue.SearchCategoryID
INNER JOIN
dbo.StockItemSearchCatVal ON dbo.SearchCategory.SearchCategoryID = dbo.StockItemSearchCatVal.SearchCategoryID
AND dbo.SearchValue.SearchValueID = dbo.StockItemSearchCatVal.SearchValueID
INNER JOIN
dbo.StockItem ON dbo.StockItemSearchCatVal.ItemID = dbo.StockItem.ItemID
I just feel I would get more benefit changing this into a subquery so that I am just returning the results to .net I am using the filehelpers library to output the results set of MapTradeItems to csv so obv more things I can do the better on the server.
Obv I would need some kind of temporary table to loop through the results but how quick would that be in sql server compared to a .net for each loop.
This is the poco class which I have to reproduce to csv.
[DelimitedRecord(",")]
public class TradeItemsExport
{
[FieldOrder(1)]
public string ItemCode { get; set; }
[FieldOrder(2)]
public string BarCode { get; set; }
[FieldOrder(3)]
public string Description { get; set; }
[FieldOrder(4)]
public string SupplierCode { get; set; }
[FieldOrder(5)]
public string SupplierStockCode { get; set; }
[FieldOrder(6)]
public string Product_Group_Code { get; set; }
[FieldOrder(7)]
public string Product_Group_Desc { get; set; }
[FieldOrder(8)]
public string SportCode { get; set; }
[FieldOrder(9)]
public string SportDesc { get; set; }
[FieldOrder(10)]
public string GenderCode { get; set; }
[FieldOrder(11)]
public string GenderDesc { get; set; }
[FieldOrder(12)]
public string ColourCode { get; set; }
[FieldOrder(13)]
public string ColourDesc { get; set; }
[FieldOrder(14)]
public string SizeCode { get; set; }
[FieldOrder(15)]
public string SizeDesc { get; set; }
[FieldOrder(16)]
public string CategoryCode { get; set; }
[FieldOrder(17)]
public string CategoryDesc { get; set; }
[FieldOrder(18)]
public string subcategorycode { get; set; }
[FieldOrder(19)]
public string subcategorydesc { get; set; }
[FieldOrder(20)]
public string BrandsCode { get; set; }
[FieldOrder(21)]
public string BrandsDesc { get; set; }
[FieldOrder(22)]
public Nullable<short> Vat { get; set; }
[FieldOrder(23)]
public decimal GrossWeight { get; set; }
[FieldOrder(24)]
public string CommodityCode { get; set; }
[FieldOrder(25)]
public decimal price_exVAT { get; set; }
[FieldOrder(26)]
public Nullable<decimal> price_incVAT { get; set; }
[FieldOrder(27)]
public Nullable<decimal> currentprice_exVAT { get; set; }
[FieldOrder(28)]
public Nullable<decimal> currentprice_incVAT { get; set; }
[FieldOrder(29)]
public System.DateTime creation_date { get; set; }
[FieldOrder(30)]
public Nullable<System.DateTime> Inactive_date { get; set; }
[FieldOrder(31)]
public int status { get; set; }
}
Hi I'm a new to elastic nest API and I'm using nest 5.x. I'm currently developing some kind of advanced search page so when user doesn't check a criteria i don't have to include that filter on my query. I'm trying to combine 2 queries under must operator with object initializer approach using nest. How to achieve it? I'm following the example on [https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/bool-queries.html]
var secondSearchResponse = client.Search(new
SearchRequest {
Query = new TermQuery { Field = Field(p => p.Name), Value = "x" } &&
new TermQuery { Field = Field(p => p.Name), Value = "y" } });
But it doesnt work cause Field class doesnt accept type arguments.
I also tried to followed this approach from this topic
[Nest Elastic - Building Dynamic Nested Query
here is my code
public HttpResponseMessage GetSearchResult([FromUri] SearchModels queries)
{
try
{
///
string result = string.Empty;
result += "queryfields + " + queries.queryfields == null ? string.Empty : queries.queryfields;
result += "datefrom + " + queries.datefrom == null ? string.Empty : queries.datefrom;
result += "dateto + " + queries.dateto == null ? string.Empty : queries.dateto;
result += "emitentype + " + queries.emitentype == null ? string.Empty : queries.emitentype;
QueryContainer andQuery = null;
//List<QueryContainer> QueryContainers = new List<QueryContainer>();
IDXNetAnnouncement record = new IDXNetAnnouncement
{
kode_emiten = queries.kodeemiten
};
#region keyword
if (!string.IsNullOrEmpty(queries.queryfields))
{
var val = queries.queryfields;
TermQuery tq = new TermQuery
{
Field = queries.queryfields,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
#endregion keyword
#region kodeemiten
if (!string.IsNullOrEmpty(queries.kodeemiten))
{
var val = queries.kodeemiten;
TermQuery tq = new TermQuery
{
Name = "kode_emiten",
Field = record.kode_emiten,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
#endregion
#region date
if (!string.IsNullOrEmpty(queries.datefrom) && !string.IsNullOrEmpty(queries.dateto))
{
DateRangeQuery dq = new DateRangeQuery();
dq.Name = "tglpengumuman";
dq.LessThanOrEqualTo = DateMath.Anchored(queries.dateto);
dq.GreaterThanOrEqualTo = DateMath.Anchored(queries.datefrom);
dq.Format = "dd/mm/yyyy";
if (andQuery == null)
andQuery = dq;
else
andQuery &= dq;
//QueryContainers.Add(dq);
}
#endregion keyword
var reqs = (ISearchResponse<IDXNetAnnouncement>)null;
if (andQuery != null)
{
reqs = conn.client.Search<IDXNetAnnouncement>(s => s
.AllIndices()
.AllTypes()
.From(queries.indexfrom)
.Size(queries.pagesize)
.Query(q => q.Bool(qb => qb.Must(m => m.MatchAll() && andQuery))));
//var json = conn.client.Serializer.SerializeToString(reqs.ApiCall.ResponseBodyInBytes);
}
else
{
reqs = conn.client.Search<IDXNetAnnouncement>(s => s
.AllIndices()
.AllTypes()
.From(queries.indexfrom)
.Size(queries.pagesize)
.Query(m => m.MatchAll()));
}
//var reqstring = Encoding.UTF8.GetString(conn.client.);
var reslts = this.conn.client.Serializer.SerializeToString(reqs,SerializationFormatting.Indented);
var resp = new HttpResponseMessage()
{
Content = new StringContent(reslts)
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return resp;
}
catch (Exception e)
{
var resp = new HttpResponseMessage()
{
Content = new StringContent(e.ToString())
};
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return resp;
}
}
But that returns zero result. How to achieve this? Thx anyway.
EDIT :
This is the params variabel definition. Its apoco model of search keywords
public class SearchModels
{
public string queryfields { get; set; }
public string datefrom { get; set; }
public string dateto { get; set; }
public string emitentype { get; set; }
public string kodeemiten { get; set; }
public string issuercode { get; set; }
public int indexfrom { get; set; }
public int pagesize { get; set; }
}
IDXNetAnnouncement is a poco model of search result. Its actualy a document type which is stored on the elastic server
public class IDXNetAnnouncement
{
public string perihalpengumuman { get; set; }
public string attachments { get; set; }
public string createddate { get; set; }
public bool efekemiten_spei { get; set; }
public string jmsxgroupid { get; set; }
public string tglpengumuman { get; set; }
public object errordescription { get; set; }
public string ESversion { get; set; }
public int oldfinalid { get; set; }
public bool efekemiten_etf { get; set; }
public object errorcode { get; set; }
public string jenisemiten { get; set; }
public int pkid { get; set; }
public string judulpengumuman { get; set; }
public string form_id { get; set; }
public bool efekemiten_eba { get; set; }
public string jenispengumuman { get; set; }
public string nopengumuman { get; set; }
public string kode_emiten { get; set; }
public string divisi { get; set; }
public string EStimestamp { get; set; }
public bool efekemiten_obligasi { get; set; }
public long finalid { get; set; }
public bool efekemiten_saham { get; set; }
public string kodedivisi { get; set; }
public string SearchTerms
{
get
{
return string.Format("{0} {1} {2}", judulpengumuman, kode_emiten, nopengumuman);
}
}
}
But it doesnt work cause Field class doesnt accept type arguments.
You need to ensure that you include a using static directive for Nest.Infer i.e.
using static Nest.Infer;
with the rest of the using directives.
.Query(q => q.Bool(qb => qb.Must(m => m.MatchAll() && andQuery))));
No need to wrap in a Must(), just do
.Query(q => q.MatchAll() && andQuery)
which will wrap both queries in a bool query must clause. You also don't need to null check andQuery because NEST is smart enough to not combine the two queries if either or both are null.
if (!string.IsNullOrEmpty(queries.queryfields))
{
var val = queries.queryfields;
TermQuery tq = new TermQuery
{
Field = queries.queryfields,
Value = val
};
if (andQuery == null)
andQuery = tq;
else
andQuery &= tq;
//QueryContainers.Add(tq);
}
NEST has the concept of conditionless queries so you don't need to check it queries.queryfields is null or empty, simply build the query and add it to andQuery. So it would become
var val = queries.queryfields;
andQuery &= new TermQuery
{
Field = queries.queryfields,
Value = val
};
Aside
All of the NEST documentation is generated from source code; you can trace back to the original source file by clicking on any edit link within the documentation. This will take you to a github page, such as this one for bool queries. From here, the document contains an important note that links back to the original source.
i have tre tables T020_CLIENTI,T021_SITI,T520_REL_STRUMENTI_SITI that i would join and then distinct by T020.Ragione_sociale,T520.DA_DATA,T520.A_DATA but obtain as return parameters T020.Ragione_sociale,T020.id_cliente,T520.cod_stumento,T520.DA_DATA,T520.A_DATA
my tables are
public partial class T020_CLIENTI
{
public decimal ID_CLIENTE { get; set; }
public Nullable<decimal> ID_COMUNE { get; set; }
public Nullable<decimal> ID_CONSORZIO { get; set; }
public string COD_LINEA_ATTIVITA { get; set; }
}
public partial class T021_SITI
{
public decimal ID_SITO { get; set; }
public Nullable<decimal> ID_FORNITORE { get; set; }
public Nullable<decimal> ID_CLIENTE { get; set; }
}
public partial class T520_REL_STRUMENTI_SITI
{
public string COD_STUMENTO { get; set; }
public decimal ID_SITO { get; set; }
public System.DateTime DA_DATA { get; set; }
public System.DateTime A_DATA { get; set; }
}
my linq query is
using (var cont = DALProvider.CreateEntityContext())
{
var query =
from cliente in cont.T020_CLIENTI
from sito
in cont.T021_SITI
.Where(s => s.ID_CLIENTE == cliente.ID_CLIENTE)
.DefaultIfEmpty()
from relStrumenti
in cont.T520_REL_STRUMENTI_SITI
.Where(s => s.ID_SITO == sito.ID_SITO)
.DefaultIfEmpty()
select new
{
clienteRec = cliente,
sitoRec = sito,
relStrumentiRec = relStrumenti
};
if (!string.IsNullOrEmpty(aiFiltro.RAGIONE_SOCIALE))
query = query.Where(i => i.clienteRec.RAGIONE_SOCIALE.ToUpper().Contains(aiFiltro.RAGIONE_SOCIALE.ToUpper()));
var vRes = (from clienteDef in query
select new ClienteFiltrato
{
RAGIONE_SOCIALE = clienteDef.clienteRec.RAGIONE_SOCIALE,
ID_CLIENTE = clienteDef.clienteRec.ID_CLIENTE,
COD_STRUMENTO = clienteDef.relStrumentiRec.COD_STUMENTO,
DATA_DA = clienteDef.relStrumentiRec.DA_DATA,
DATA_A = clienteDef.relStrumentiRec.A_DATA
}) ;
return vRes.AsQueryable();
}
but in my linq query i don't know where i can insert distinct and input parameter (:pPOD) to obtain my linq that in oracle query is:
SELECT DISTINCT t020.ragione_sociale,
da_data,
a_data,
t020.id_Cliente,
:pPOD
FROM t020_clienti t020, t021_siti t021, T520_REL_STRUMENTI_SITI t520
WHERE t020.id_cliente = t021.id_cliente
AND t021.id_sito = t520.id_sito
AND (:pPOD is null or t520.cod_stumento = :pPOD)
ORDER BY da_data
where :pPOD is an input parameter that i could have set or not.
Try to add (s.COD_STUMENTO == pPod || pPod == null) to your Where clause, where you are filtering T520_REL_STRUMENTI_SITI entity. pPod should be a string variable.
Please have in mind that if you are using DefaultIfEmpty() in LINQ this will be translated to left join in SQL.
Modified query follows:
string pPod = null;
using (var cont = DALProvider.CreateEntityContext())
{
var query =
(from cliente in cont.T020_CLIENTI
from sito
in cont.T021_SITI
.Where(s => s.ID_CLIENTE == cliente.ID_CLIENTE)
.DefaultIfEmpty()
from relStrumenti
in cont.T520_REL_STRUMENTI_SITI
.Where(s => s.ID_SITO == sito.ID_SITO && (s.COD_STUMENTO == pPod || pPod == null))
.DefaultIfEmpty()
select new
{
clienteRec = cliente.Distinct(),
sitoRec = sito,
relStrumentiRec = relStrumenti
});
if (!string.IsNullOrEmpty(aiFiltro.RAGIONE_SOCIALE))
query = query.Where(i => i.clienteRec.RAGIONE_SOCIALE.ToUpper().Contains(aiFiltro.RAGIONE_SOCIALE.ToUpper()));
var vRes = (from clienteDef in query
select new ClienteFiltrato
{
RAGIONE_SOCIALE = clienteDef.clienteRec.RAGIONE_SOCIALE,
ID_CLIENTE = clienteDef.clienteRec.ID_CLIENTE,
COD_STRUMENTO = clienteDef.relStrumentiRec.COD_STUMENTO,
DATA_DA = clienteDef.relStrumentiRec.DA_DATA,
DATA_A = clienteDef.relStrumentiRec.A_DATA
}).Distinct() ;
return vRes.AsQueryable();
}
You can use:
string query =
((System.Data.Objects.ObjectQuery)query).ToTraceString();
This will show you the generated SQL from LINQ Queryable object.
I'm trying to import data from excel using LinqToExcel. I have few readonly properties in the model class. When I try to map them with the excel columns, they fail with following error. Also when I drop those columns from excel, it works fine without values.
Method 'Total' not found.
Model:Budget
[Required]
[Display(Name = "Room Type")]
public int RoomTypeID { get; set; }
[ForeignKey("RoomTypeID")]
public virtual RoomType RoomType { get; set; }
public decimal Pair { get; set; }
[ExcelColumn("Cost per Room*")]
public decimal CostPerRoom { get; set; }
[NotMapped]
[ExcelColumn("Total")]
[Display(Name = "Total")]
public decimal Total
{
get
{
if (this.RoomType != null)
{
return this.CostPerRoom * this.RoomType.RoomTypeQty * this.Pair;
}
else
{
return 0;
}
}
}
Budget Controller:
public ActionResult ReadFromExcel()
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads/"), fileName);
file.SaveAs(path);
var excel = new ExcelQueryFactory(path);
excel.DatabaseEngine = DatabaseEngine.Ace;
excel.TrimSpaces = LinqToExcel.Query.TrimSpacesType.Both;
var budgets = from c in excel.Worksheet<Budget>("WorksheeName") select c;
foreach (var item in budgets) // This is where it generates the error.
{
}
}
How do I overcome this?
I have the following class objects:
public class VacancyCategory
{
public int ID { get; set; }
public string Text { get; set; }
public IList<VacancySubCategory> SubCategories { get; set; }
}
public class VacancySubCategory
{
public int ID { get; set; }
public string Text { get; set; }
public VacancyCategory Category { get; set; }
public IList<Vacancy> Vacancies { get; set; }
}
public class Vacancy : IBusinessObject
{
public int ID { get; set; }
public string Title { get; set; }
public VacancySubCategory SubCategory { get; set; }
public string Body { get; set; }
public VacancyWorkType WorkType { get; set; }
public string Salary { get; set; }
public DateTime? AppsClosingDate { get; set; }
public bool Active { get; set; }
}
...so in a test repository im creating test data like so:
private IList<VacancyCategory> GetVacancyCategoriesWithAllChildCollections()
{
IList<VacancyCategory> vacancyCategories = new List<VacancyCategory>();
int cCounter = 0;
int scCounter = 0;
int vCounter = 0;
for (int i = 1; i <= 3; i++)
{
VacancyCategory vc = new VacancyCategory();
vc.ID = ++cCounter;
vc.Text = "VacancyCategory" + i.ToString();
for (int j = 1; j <= 3; j++)
{
VacancySubCategory vsc = new VacancySubCategory();
vsc.ID = ++scCounter;
vsc.Text = "VacancySubCategory" + scCounter.ToString();
vsc.Category = vc;
for (int k = 1; k <= 2; k++)
{
Vacancy v = new Vacancy();
v.ID = ++vCounter;
v.Title = "Vacancy" + vCounter.ToString();
v.Body = "VacancyBody" + vCounter.ToString();
v.Active = vCounter >= 16 ? false : true;
v.WorkType = this._workTypes.Single(wt => wt.ID == k);
v.Salary = vCounter <= 7 ? "SR " + (vCounter * 1000).ToString() : "";
v.AppsClosingDate = (vCounter >= 3 & vCounter <= 13) ? (new DateTime(2009, 3, vCounter)) : (DateTime?)null;
v.SubCategory = vsc;
if (vsc.Vacancies == null)
vsc.Vacancies = new List<Vacancy>();
vsc.Vacancies.Add(v);
}
if (vc.SubCategories == null)
vc.SubCategories = new List<VacancySubCategory>();
vc.SubCategories.Add(vsc);
}
vacancyCategories.Add(vc);
}
return vacancyCategories;
}
..so now i have some good test data. the object tree / chained objects are important to me.
so i'd like to return the individual object collections from this tree when desired. for example, if i wanted the whole tree, i can just return the VacancyCategory list with all the child objects - great. but now i want to return just the VacancySubCaregory items (all 9 of them). this would be my public method to the test repository:
public IQueryable<VacancySubCategory> GetVacancySubCategories()
{
throw new NotImplementedException("write gen code");
}
.. obviously without the exception. i have a member field called _categories that contains the results from the GetVacancyCategoriesWithAllChildCollections method. so i've been trying stuff like
this._categories.Select( ......
..but i cant seem to return a list of VacancySubCategory objects. i seem to always be selecting the root collection (ie. a result set of VacancyCategory objects). What am i doing wrong? im sure its simple... but its driving me nuts!
EDIT
thanx matt.
your suggestion led me to this:
public IQueryable<VacancySubCategory> GetVacancySubCategories()
{
return this._categories.SelectMany(c => c.SubCategories).AsQueryable<VacancySubCategory>();
}
..which works great. you're a champ
Try:
return this._categories.SelectMany(c => c.SubCategories);
This should work.
var query = from vc in GetVacancyCategoriesWithAllChildCollections()
from vcs in vc.SubCategories
select vcs