I think now i know where is the problem but i do not know i will fix that.
Actually i am fetching data through entityFramework 4.1 and since my search criteria is dynamic so i have only one way to do that which i kenter code herenow which is
using System;
using System.Linq;
using System.Data.Entity;
using QTrac.Models;
using System.Transactions;
namespace QTrac.DAL
{
public class AssetManagementSearchRepository : RepositoryBase<AssetManagementSearch>, IAssetManagementSearchRepository
{
public AssetManagementSearchRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { }
#region IAssetManagementSearchResponseRepository Members
public IQueryable<AssetManagementSearch> GetSearchResult(SearchRequest request)
{
IQueryable<AssetManagementSearch> query = DbSet;
using (var context = new QTracContext()) {
using (var tx = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = IsolationLevel.ReadUncommitted })) {
//try {
if (!String.IsNullOrEmpty(request.FileCode)) {
query = query.Where(d => d.FileCode.StartsWith(request.FileCode));
}
if (!String.IsNullOrEmpty(request.SerialNo)) {
query = query.Where(d => d.SerialNo.StartsWith(request.SerialNo));
}
if (!String.IsNullOrEmpty(request.TopLevelEquipment)) {
query = query.Where(d => d.ParentToolSet.StartsWith(request.TopLevelEquipment));
}
if (!String.IsNullOrEmpty(request.EquipmentState)) {
query = query.Where(d => d.EqpState.StartsWith(request.EquipmentState));
}
if (!String.IsNullOrEmpty(request.EquipmentStatus)) {
query = query.Where(d => d.EqpStatus.StartsWith(request.EquipmentStatus));
}
if (!String.IsNullOrEmpty(request.DFP)) {
query = query.Where(d => d.DFP.StartsWith(request.DFP));
}
if (request.Active.HasValue) {
query = query.Where(d => d.IsActive == request.Active);
}
if (!String.IsNullOrEmpty(request.OwnerSite)) {
query = query.Where(d => d.OwnerSite.StartsWith(request.OwnerSite));
}
if (!String.IsNullOrEmpty(request.ControlSite)) {
query = query.Where(d => d.ControlSite.StartsWith(request.ControlSite));
}
if (!String.IsNullOrEmpty(request.Location)) {
query = query.Where(d => d.Location.StartsWith(request.Location));
}
if (!String.IsNullOrEmpty(request.StampedFC)) {
query = query.Where(d => d.STAMPEDFC.StartsWith(request.StampedFC));
}
if (!String.IsNullOrEmpty(request.StampedSN)) {
query = query.Where(d => d.STAMPEDSN.StartsWith(request.StampedSN));
}
if (!String.IsNullOrEmpty(request.CustomsStatus)) {
query = query.Where(d => d.CustomsStatus.StartsWith(request.CustomsStatus));
}
if (!String.IsNullOrEmpty(request.ImportType)) {
query = query.Where(d => d.ImportType.StartsWith(request.ImportType));
}
if (!String.IsNullOrEmpty(request.ClientBasket)) {
query = query.Where(d => request.ClientBasket.Contains(d.ClientBasket));
}
if (!String.IsNullOrEmpty(request.ImportClient)) {
query = query.Where(d => request.ImportClient.Contains(d.ImportClient));
}
if (!String.IsNullOrEmpty(request.AssignedClient)) {
query = query.Where(d => d.AssignedClient.StartsWith(request.AssignedClient));
}
if (!String.IsNullOrEmpty(request.FileCodesByToolFamily)) {
query = query.Where(d => request.FileCodesByToolFamily.Contains(d.FileCode));
}
return query.AsNoTracking();
//}
//catch(Exception e) {
// throw e.InnerException;
//}
//finally {
// //Context.Dispose();
//}
}
}
}
#endregion
}
}
usually it works fine, One case it does not work when i download my code from source control, 2nd is yesterday i was working on same solution but different page i added many views and strored procedures in .edmx file and when i tested this search screen it was not working it was returning 500 error everytime, 500 error i traped from mvc telerik grid error event.
If i change this code to without dynamic like
return Get(filter: p => p.ACTIVE == active, orderBy: o => o.OrderBy(p => p.NAME), tracking: false);
then search start working.
Please tell me the issue.
Thanks
Related
Basically I want to sort them based on the highest - lowest avg rating but I can't do it since I've already fetched the data (paginate(12)).
Adding sortBy in the if else section is not possible since I do not have yet the avg_rating data. I tried it after foreach but keeps throwing error.
Any workarounds here so I can dynamically sort it out?
public function render()
{
$recipe_default = Recipe::where('is_approved', 1);
if(is_null($this->name_atoz))
{
$recipe_default = $recipe_default->orderBy('id', 'asc')->paginate(12);
}
elseif($this->name_atoz == true)
{
$recipe_default = $recipe_default->orderBy('recipe_name')->paginate(12);
}
elseif($this->name_atoz == false)
{
$recipe_default = $recipe_default->orderBy('recipe_name', 'desc')->paginate(12);
}
foreach($recipe_default as $key => $value)
{
$recipe_default[$key]->avg_rating = Feedback::where('recipe_id', $value->id)->avg('rating');
$recipe_default[$key]->feedback_count = Feedback::where('recipe_id', $value->id)->count();
$recipe_default[$key]->tag_name = Taggable::where('taggable_id', $value->id)->where('taggable_type', 'recipe')->value('tag_name');
}
return view('livewire.content-management', [
'recipes' => $recipe_default
]);
}
I have a query and want to do a search by multiple fields in case if no result by uuid need to do the same by parentUuid:
C# query:
return new NestedQuery
{
Path = Infer.Field<ElasticDocument>(t => t.KeywordFields),
Query = new BoolQuery
{
Filter = new List<QueryContainer>
{
new TermsQuery
{
Field = Infer.Field<ElasticDocument>(t => t.KeywordFields),
Terms = new List<string>
{
"term2"
},
Boost = 10
}
},
Should = new List<QueryContainer>
{
new TermQuery
{
Field = Infer.Field<ElasticDocument>(t => t.KeywordFields.First().UUID),
Value = filter.UUID
},
new TermQuery
{
Field = Infer.Field<ElasticDocument>(t => t.KeywordFields.First().ParentUUID),
Value = filter.UUID
},
}
}
};
example of documents:
"keywordFields": [
{
"value": "term1",
"uuid": "bf18ee9f-7592-488d-7985-2b9fe8b878ca",
"parentUUID": null
},
{
"value": "term2",
"uuid": "079205ed-30df-08f6-02a1-9caf093c3be0",
"parentUUID": "103d6061-cb99-4fba-8118-2ea501e4425d"
}
]
How to update the query to use or condition in case if no result by 'UUID' then let's do it by ParentUUID?
Try to combine bool query:
nested1 = new NestedQuery {
Path = Infer.Field<ElasticDocument>(t => t.KeywordFields),
Query = new BoolQuery {
Filter = new List<QueryContainer>
{
new TermsQuery {
Field = Infer.Field<ElasticDocument>(t => t.KeywordFields),
Terms = new List<string>
{
"term2"
},
Boost = 10
}
}
}
};
nested2 = new NestedQuery {
Path = Infer.Field<ElasticDocument>(t => t.KeywordFields),
Query = new BoolQuery {
Filter = new List<QueryContainer>
{
new TermsQuery {
Field = Infer.Field<ElasticDocument>(t => t.KeywordFields),
Terms = new List<string>
{
"term2"
},
Boost = 10
}
},
Should = new List<QueryContainer>
{
new BoolQuery {
MustNot = new List<QueryContainer> {
new TermQuery
{
Field = Infer.Field<ElasticDocument>(t => t.KeywordFields.First().UUID),
Value = filter.UUID
}
},
Must = new List<QueryContainer> {
new TermQuery
{
Field = Infer.Field<ElasticDocument>(t => t.KeywordFields.First().parentUUID),
Value = filter.UUID
}
}
}
}
}
};
And should nested1 with nested2
note: not IDE for this edit, the nested2 query could be simplify for sure.
I cannot get the following to work properly. I want to search my database using more than 2 conditions where it will be possible to search only on one, two or all three, thus narrowing the search. At the moment, I can only get it to work with one condition at a time, and it only evaluates the first condition when having more than 3.
How can I Include more than 2 conditions? I have tried several proposed solutions from other sources, that uses if statements and where clauses, but so far none of them have worked.
This is my controller
public IActionResult Index(string searchString, int searchProject, string searchTitel)
{
var Projektdokumenter = from p in _context.ProjekterDokutypeDokuundertype
.Include(p => p.Dokumenttype)
.Include(p => p.Dokuundertype)
.Include(p => p.Forfatter)
.Include(p => p.P)
.Include(p => p.Sprog)
select p;
if (!String.IsNullOrEmpty(searchString) ^ searchProject != null ^ !String.IsNullOrEmpty(searchTitel))
{
if (!String.IsNullOrEmpty(searchString))
{
var c = Projektdokumenter.Where(p => p.Forfatter.Initialer.Contains(searchString)).ToList();
return View(c);
}
{
if (searchProject != 0)
{
var d = Projektdokumenter.Where(p => p.P.ProjektId.Equals(searchProject)).ToList();
return View(d);
}
{
if(!String.IsNullOrEmpty(searchTitel))
{
var f = Projektdokumenter.Where(p => p.Titel.Contains(searchTitel)).ToList();
return View(f);
}
}
}
}
var e = Projektdokumenter.Where(c.Contains(searchString) && p.P.ProjektId.Equals(searchProject) && p.Titel.Contains(searchTitel)).ToList();
return View(e);
}
IQueryable can be combined, so just write in native way:
{
var query = _context.ProjekterDokutypeDokuundertype
.Include(p => p.Dokumenttype)
.Include(p => p.Dokuundertype)
.Include(p => p.Forfatter)
.Include(p => p.P)
.Include(p => p.Sprog)
.AsQueryable();
if (!string.IsNullOrEmpty(searchString))
{
query = query.Where(p => p.Forfatter.Initialer.Contains(searchString));
}
if (searchProject != 0)
{
query = query.Where(p => p.P.ProjektId == searchProject);
}
if (!string.IsNullOrEmpty(searchTitel))
{
query = query.Where(p => p.Titel.Contains(searchTitel))
}
return View(query.ToList());
}
I am able to create new record in TreeList for MVC. But it shows newly created record only after refreshing the page. Edit and Delete works fine.
Razor Code
#(Html.Kendo().TreeList<KendoEx.Web.Models.Level>()
.Name("lvlTreeList")
.Toolbar(toolbar =>
{
toolbar.Create();
})
.Columns(columns =>
{
columns.Add().Field(e => e.LvlName).Title("Name").Width(120);
columns.Add().Field(e => e.LvlType).Title("Type").Width(80);
columns.Add().Field(e => e.Rating1).Title("Rating 1").Filterable(false).Width(100);
columns.Add().Field(e => e.Rating2).Title("Rating 2").Filterable(false).Width(100);
columns.Add().Command(c =>
{
c.CreateChild().Text("Add child");
c.Edit();
c.Destroy();
}).Width(180);
})
.Editable(e => e.Mode("inline"))
.DataSource(dataSource => dataSource
.Read(read => read.Action("GetLevel", "Level"))
.Create(create => create.Action("Save", "Level"))
.Update(update => update.Action("Save", "Level"))
.Destroy(delete => delete.Action("Remove", "Level"))
.Model(m =>
{
m.Id(f => f.Id);
m.ParentId(f => f.ParentLvl).DefaultValue(0);
m.Expanded(true);
m.Field(f => f.LvlName);
m.Field(f => f.LvlType);
m.Field(f => f.Rating1);
m.Field(f => f.Rating1);
}))
.Height(550))
Controller Methods
public JsonResult GetLevel([DataSourceRequest] DataSourceRequest request)
{
var lvlList = LoadLevels().ToTreeDataSourceResult(request);
return Json(lvlList, JsonRequestBehavior.AllowGet);
}
private IEnumerable<Level> LoadLevels()
{
IEnumerable<Level> lvlList = Enumerable.Empty<Level>(); ;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["WebApiExUrl"]);
var responseTask = client.GetAsync("getlevel");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<FormattedResult<Level>>();
readTask.Wait();
if (string.IsNullOrEmpty(readTask.Result.Error))
{
IEnumerable<Level> tempList = readTask.Result.Data;
lvlList = tempList.Select(m => new Level
{
Id = m.Id,
LvlName = m.LvlName,
LvlType = m.LvlType,
ParentLvl = m.ParentLvl,
Rating1 = m.Rating1,
Rating2 = m.Rating2,
hasChildren = tempList.Where(s => s.ParentLvl == m.Id).Count() > 0
});
}
}
}
return lvlList;
}
public JsonResult Save([DataSourceRequest] DataSourceRequest request, Level level)
{
if (level != null && ModelState.IsValid)
{
try
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ConfigurationManager.AppSettings["KpiApiUrl"]);
var postTask = client.PostAsJsonAsync("savelevel", level);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsStringAsync();
readTask.Wait();
}
}
}
catch (Exception ex)
{
ModelState.AddModelError(string.Empty, "Unexpected error");
}
}
return Json(new[] { level }.ToTreeDataSourceResult(request, ModelState));
}
Model
public class Level
{
public int Id { get; set; }
public string LvlName { get; set; }
public string LvlType { get; set; }
public int? ParentLvl { get; set; }
[RegularExpression(#"^(\d{1,2}(\.\d{0,2})?)?(<|<=|>|>=)(\d{1,3}(\.\d{0,2})?)$", ErrorMessage = "Invalid")]
public string Rating1 { get; set; }
[RegularExpression(#"^(\d{1,2}(\.\d{0,2})?)?(<|<=|>|>=)(\d{1,3}(\.\d{0,2})?)$")]
public string Rating2 { get; set; }
}
If the 'Save' method returns
return Json(LoadLevels().ToDataSourceResult(request, ModelState), JsonRequestBehavior.AllowGet);
instead of
return Json(new[] { level }.ToTreeDataSourceResult(request, ModelState));
the TreeList shows duplicate records
The 'Save' event of TreeList also behaves in the same way.
function onSave() {
$("#lvlTreeList").data("kendoTreeList").dataSource.read();
}
Version Info: Telerik 2018.1.221.545, MVC 5.2, .NET 4.6
Please advise on this. Thanks.
Demo Link: https://demos.telerik.com/aspnet-mvc/treelist/editing
Calling read() in Sync event of DataSource, refreshes the TreeList and displays newly created level.
Razor Code
#(Html.Kendo().TreeList<..>()
.Name("lvlTreeList")
/*..*/
.DataSource(dataSource => dataSource
.Events(e => e.Sync("lvlTreeList_Sync"))
/*...*/
))
Javascript
<script>
function lvlTreeList_Sync() {
this.read();
}
</script>
Refer: https://www.telerik.com/forums/refresh-after-upda
I'm trying to implement a result filter with MVC3 and face a problem like this:
public ActionResult Index(int? SubID)
{
var product = db.Product.Where(s => s.SubID == SubID).Include(t => t.SubCategory);
if (SubID.HasValue)
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN", SubID);
}
else
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN");
}
return View(product);
}
This one above works fine, but the following one always give me result of the whole table, despite what condition I put on it:
public ActionResult Index(int? SubID)
{
var product = db.Product.Include(t => t.SubCategory);
if (SubID.HasValue)
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN", SubID);
product.Where(s => s.SubID == SubID);
}
else
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN");
}
return View(product);
}
And even this one doesn't work too:
public ActionResult Index(int? SubID)
{
var product = from m in db.Product
select m;
if (SubID.HasValue)
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN", SubID);
product.Where(s => s.SubID == SubID);
}
else
{
ViewBag.SubID = new SelectList(db.SubCategory, "SubID", "SubNameVN");
}
product.Include(t => t.SubCategory);
return View(product);
}
So please tell me what is the difference between these 3 approaches, and please explain to me why #2 and #3 don't work?
product.Where(s => s.SubID == SubID);
...does not add a condition on product, it just creates an IEnumerable with the condition applied, and immediately throws it away. What you want is probably;
product = product.Where(s => s.SubID == SubID);