I'm using System.Linq.Dynamic to make dinanmico where in my research. In the code below I try to filter by Funcao, but returns the error:
No property or field 'Funcao' exists in type 'ASO'
How do I filter by an alias of my Linq?
CODE
public static ResultadoListagemPadrao Grid(int iniciarNoRegistro, int qtdeRegistro, string orderna, string ordenaTipo, string filtro, int filtroID, UsuarioLogado usuarioLogado)
{
var where = "";
var id = 0;
if (filtroID > 0)
where += " FuncionarioID == " + filtroID.ToString();
else
{
if (int.TryParse(filtro, out id))
where += " ASOID == " + id.ToString();
if (filtro != null)
where += " Funcao.Contains(#0) ";
}
using (var db = new ERPContext())
{
var resultado = new ResultadoListagemPadrao();
resultado.TotalRegistros = db.ASO.Total(usuarioLogado.EmpresaIDLogada);
resultado.TotalRegistrosVisualizados = db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable().Where(where, filtro).Count();
resultado.Dados =
(from a in db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable()
select new
{
a.ASOID,
a.FuncionarioID,
Cliente = a.Funcionario.Cliente.Pessoa.Nome,
Setor = a.FuncionarioFuncao.Funcao.Setor.Descricao,
Funcao = a.FuncionarioFuncao.Funcao.Descricao,
Funcionario = a.Funcionario.Pessoa.Nome,
a.DtASO,
a.Status
})
.Where(where, filtro)
.OrderBy(orderna + " " + ordenaTipo)
.Skip(iniciarNoRegistro)
.Take(qtdeRegistro)
.ToArray();
return resultado;
}
}
Issue is this line db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable().Where(where, filtro)
Your class ASO doesn't have a property Funcao.
Try remove the Where on that line. Try this...
var resultado = new ResultadoListagemPadrao();
resultado.TotalRegistros = db.ASO.Total(usuarioLogado.EmpresaIDLogada);
var query = (from a in db.ASO.ToListERP(usuarioLogado.EmpresaIDLogada).AsQueryable()
select new
{
a.ASOID,
a.FuncionarioID,
Cliente = a.Funcionario.Cliente.Pessoa.Nome,
Setor = a.FuncionarioFuncao.Funcao.Setor.Descricao,
Funcao = a.FuncionarioFuncao.Funcao.Descricao,
Funcionario = a.Funcionario.Pessoa.Nome,
a.DtASO,
a.Status
})
.Where(where, filtro);
resultado.TotalRegistrosVisualizados = query.Count();
resultado.Dados = query
.OrderBy(orderna + " " + ordenaTipo)
.Skip(iniciarNoRegistro)
.Take(qtdeRegistro)
.ToArray();
return resultado;
Please in future translate your code.
Related
I have some code that I want to be able to reuse. To do this I need to pass the DbSet type in dynamically. How would I get this to work?
public virtual DbSet<Runlist> Runlists { get; set; }
public void Method(Type myType)
{
using (var ctx = new FpContext())
{
Type myVariableType = myType;
var table = "myTable";
var sql = ctx.Database
.SqlQuery<myVariableType>("SELECT * FROM #table WHERE (UserId = #userid)"
, new SqlParameter("#userid", user.Id)
, new SqlParameter("#table", table)).ToList();
}
foreach (var r in sql)
{
foreach (XElement e in xmlDoc.Descendants(ns + "RateRequest"))
{
var originCode = e.Element(ns + "RequestedShipment").Element(ns + "Shipper").Element(ns + "Address").Element(ns + "PostalCode");
var postalCode = e.Element(ns + "RequestedShipment").Element(ns + "Recipient").Element(ns + "Address").Element(ns + "PostalCode");
var shipTime = e.Element(ns + "RequestedShipment").Element(ns + "ShipTimestamp");
var serviceType = e.Element(ns + "RequestedShipment").Element(ns + "ServiceType");
var totalWeight = e.Element(ns + "RequestedShipment").Element(ns + "TotalWeight").Element(ns + "Value");
var packageCount = e.Element(ns + "RequestedShipment").Element(ns + "PackageCount");
var weight = e.Element(ns + "RequestedShipment").Element(ns + "RequestedPackageLineItems").Element(ns + "Weight").Element(ns + "Value");
originCode.SetValue(origin);
postalCode.SetValue(r.Zipcode);
shipTime.SetValue(dt);
serviceType.SetValue("FEDEX_GROUND");
totalWeight.SetValue(r.TotalWeight);
packageCount.SetValue(r.BoxCount);
weight.SetValue(r.Weight);
}
xmlDoc.Save(HttpContext.Current.Server.MapPath("~/Requests/SoapRequest_v24.xml"));
}
}
I have posted additional code to try and explain more to what I am trying to accomplish.
If you are using SqlQuery method from EntityFramework there is an overload that receives the type as parameter, so your code could be something like:
public void Method(Type myType)
{
using (var ctx = new FpContext())
{
Type myVariableType = myType;
var table = "myTable";
var sql = ctx.Database
.SqlQuery(myVariableType, "SELECT * FROM #table WHERE (UserId = #userid)"
, new SqlParameter("#userid", user.Id)
, new SqlParameter("#table", table)).ToList();
}
}
You can check that method here.
I need to bind the search result from NEST (ElasticSearch) to a Gridview in ASP.NET (Webform).
Code I get the result from ElasticSearch from using NEST:
public class Address
{
public int SN { get; set; }
public string JLN { get; set; }
}
protected void BtnSearch_Clicked(object sender, EventArgs e)
{
string SearchValue = txtSearchValue.Text;
string es_host = System.Configuration.ConfigurationManager.AppSettings["cnStringIP"];
string es_port = System.Configuration.ConfigurationManager.AppSettings["cnStringPort"];
string es_index = System.Configuration.ConfigurationManager.AppSettings["cnStringIndex"];
var settings = new ConnectionSettings(new Uri("http://" + es_host + ":" + es_port + ""))
.DefaultIndex("masterlist*");
var client = new ElasticClient(settings);
var searchResponse = client.Search<Address>(s => s
.Index("masterlist*")
.From(0)
.Size(10)
.Query(q => q
.QueryString(qs => qs
.Query("JLN:\""+ SearchValue +"\"")
)
)
);
var address = searchResponse.Documents.ToList();
ESGridview.DataSource = address;
ESGridview.DataBind();
}
With this code, the gridview can auto-generate two fields of correct header which is "SN" and "JLN", and it can auto generate 10 rows (I limit the size to 10 rows max in search syntax) but it's empty data in the column.
I did found another POST with this link
https://www.elastic.co/guide/en/elasticsearch/client/net-api/6.x/returned-fields.html#returned-fields
After check with this link,
I changed my code to:
string SearchValue = txtSearchValue.Text;
string es_host = System.Configuration.ConfigurationManager.AppSettings["cnStringIP"];
string es_port = System.Configuration.ConfigurationManager.AppSettings["cnStringPort"];
string es_index = System.Configuration.ConfigurationManager.AppSettings["cnStringIndex"];
var settings = new ConnectionSettings(new Uri("http://" + es_host + ":" + es_port + ""))
.DefaultIndex("masterlist*");
var client = new ElasticClient(settings);
var searchResponse = client.Search<Address>(s => s
.StoredFields(sf => sf
.Fields(
f => f.SN,
f => f.JLN
)
)
.From(0)
.Size(10)
.Query(q => q
.QueryString(qs => qs
.Query("JLN:\""+ SearchValue +"\"")
)
)
);
foreach (var fieldValues in searchResponse.Fields)
{
var document = new
{
SN = fieldValues.ValueOf<Address, int>(p => p.SN),
JLN = fieldValues.Values<Address, string>(p => p.JLN)
};
}
var address = searchResponse.Documents;
var count = "MaxScore" + searchResponse.MaxScore;
ESGridview.DataSource = address;
ESGridview.DataBind();
But I get an error while run the code from start on whole foreach (var...) area :
System.NullReferenceException:'Object reference not set to an instance of an object.'
Did anyone can teach me how can solve this problem or anything I do fault ?
Many many thanks ~
ElasticSearch 7.0.1
NEST 7.0.0
C#
ASP.NET (Webform)
I solve my problem already.
The code below is how to get the searchResult from ElasticSearch and bind the data into Gridview in ASP.NET by using NEST.
public class Address
{
[Text(Name = "SN")]
public string SN { get; set; }
[Text(Name = "JLN")]
public string JLN { get; set; }
}
protected void BtnSearch_Clicked(object sender, EventArgs e)
{
string SearchValue = txtSearchValue.Text;
string es_host = System.Configuration.ConfigurationManager.AppSettings["cnStringIP"];
string es_port = System.Configuration.ConfigurationManager.AppSettings["cnStringPort"];
string es_index = System.Configuration.ConfigurationManager.AppSettings["cnStringIndex"];
var settings = new ConnectionSettings(new Uri("http://" + es_host + ":" + es_port + ""))
.DefaultIndex("masterlist*");
var client = new ElasticClient(settings);
var searchResponse = client.Search<Address>(s => s
.From(0)
.Size(100)
.Query(q => q
.QueryString(qs => qs
.Query("JLN:\"" + SearchValue + "\"")
)
)
);
var address = searchResponse.Documents.ToList();
ESGridview.DataSource = address;
ESGridview.DataBind();
}
In the code below, I would like the return from GetChainDetails to go where i have "I WANT MY LIST HERE" in GetChains method. Not sure how to accomplish or what other way to do this.
public static IEnumerable GetChains(int actGroupid, int dispid)
{
EEDBEntities db = new EEDBEntities();
var query = from c in db.Chains
where c.Activity_Basis.activity_group_id == actGroupid && c.Activity_Basis.discipline_id == dispid
select new
{
ChainID = c.ChainID,
ChainDesc = #"<span data-toggle=""tooltip"" title =""" + I WANT MY LIST HERE + #""">" + c.ChainID + "</span>"
};
return query.ToList();
}
public string GetChainDetails(string chainID)
{
string sStep = null;
var chainDetailList = from c in db.Chains_Detail
where c.chainID == chainID
orderby c.Order
select new
{
Order = c.Order,
Step = c.Step
};
foreach (var oItem in chainDetailList.ToList())
{
sStep = sStep + "\n" + oItem.Order + ": " + oItem.Step;
}
return sStep;
}
Your method public string GetChainDetails(string chainID) is not static. Perhaps this is the reason you are getting error. Make it static and try and run the code.
public static string GetChainDetails(string chainID)
Also you can follow this approach :
class X
{
public int Property1;
public int Property2;
public string ChainID;
public string MyListToolTipText;
}
class Y
{
public string ChainID;
public string ChainDesc;
}
And your main code
class Program
{
static void Main()
{
var myResult = GetChains(1, 1);
foreach (var result in myResult)
{
result.ChainDesc = GetChainDetails(result.ChainID);
}
//you can use either foreach or linq
//var m = myResult.Select(result => result = new Y { ChainID = result.ChainID, ChainDesc = GetChainDetails(result.ChainDesc) });
}
public static IEnumerable<Y> GetChains(int actGroupid, int dispid)
{
var Chains = new List<X>();
var query = from c in Chains
where c.Property1 == actGroupid && c.Property2 == dispid
select new Y
{
ChainID = c.ChainID,
ChainDesc = #"<span data-toggle=""tooltip"" title =""" + c.MyListToolTipText + #""">" + c.ChainID + "</span>"
};
return query.ToList<Y>();
}
public static string GetChainDetails(string chainID)
{
string sStep = null;
var chainDetailList = from c in db.Chains_Detail
where c.chainID == chainID
orderby c.Order
select new
{
Order = c.Order,
Step = c.Step
};
foreach (var oItem in chainDetailList.ToList())
{
sStep = sStep + "\n" + oItem.Order + ": " + oItem.Step;
}
return sStep;
}
}
Hence after calling GetChains, I am modifying each member property.
I have Lots of collection list in my page what i want to do just
merge all collection list into single collection list in entity
framework.I already Defined class or model but when i retrieve it
doesn't return any thing.
using (FinanceEntities fentities = new FinanceEntities(value.credentials))
{
try
{
int str=DateTime.DaysInMonth(Valcol.year,Valcol.month);
string FD = Valcol.year + "-" + Valcol.month + "-" + "01";
string LD = Valcol.year + "-" + Valcol.month + "-" + str;
DateTime FirstDate = DateTime.Parse(FD);
DateTime vdate = DateTime.Parse(LD);
List<PayNoModel> PayNoModel = GetPayNoModel(value);
List<VoucherNoModel> VoucherNoModel=GetVoucherNoModel(value);
List<PayNoModel> PayNoModel2 = GetPayNoModel2(value);
List<PayNoModel> PayNoModel3 = GetPayNoModel3(value);
List<VoucherNoModel> VoucherNoModel2 = GetVoucherNoModel2(value);
List<ChequeNoModel> ChequeNoModel = GetChequeNoModel(value);
List<VoucherNoDiffModel> VoucherNoDiffModel = GetVoucherNoDiffModel(value);
List<VoucherNoNarationModel> VoucherNoNarationModel = GetVoucherNoNarationModel(value);
query = (from p in PayNoModel
from v in VoucherNoModel
from p2 in PayNoModel2
from p3 in PayNoModel3
from v2 in VoucherNoModel
from ch in ChequeNoModel
from voucdiff in VoucherNoDiffModel
from voucnarr in VoucherNoNarationModel
select new ReconcileReportModel
{
}).ToList<ReconcileReportModel>();
}
catch (Exception ex)
{
var s = ex.Message;
}
}
return query;
}
I'm binding a drop down to a radcombobox like this
_ddActQuota.DataTextField = "DESC";
_ddActQuota.DataValueField = "ID";
_ddActQuota.DataSource = LNQ.tbl_job_quotas.Where(c => c.job_quota_job_number == _fJ).Select(c => new { ID = c.job_quota_ID, DESC = c.job_quota_ID + " | " + c.job_quota_desc });
_ddActQuota.DataBind();
How can I add a initial value of ID="%%" DESC="ALL". Doing it in the markup does not work in this instance.
var LNQ = new LNQDataContext();
var quo = LNQ.tbl_job_quotas.Where(c => c.job_quota_job_number == _fJ).Select(c => new { ID = c.job_quota_ID, DESC = c.job_quota_ID + " | " + c.job_quota_desc });
var DtQu = new DataTable();
DtQu.Columns.Add("ID");
DtQu.Columns.Add("DESC");
DataRow drs;
drs = DtQu.NewRow();
drs[0] = "%%";
drs[1] = "ALL";
DtQu.Rows.Add(drs);
foreach (var a in quo)
{
drs = DtQu.NewRow();
drs[0] = a.ID;
drs[1] = a.DESC;
DtQu.Rows.Add(drs);
}
_ddActQuota.DataTextField = "DESC";
_ddActQuota.DataValueField = "ID";
_ddActQuota.DataSource = DtQu;
_ddActQuota.DataBind();