my Problem With Read by Foreach when Query and Create Two Level RelationShip like This:
Lambda:
public IList GetMasterDetailsFilterLang(string language)
{
var query = (_ourServiceCategories
.Where(c => (c.Language == "fa-IR"))
.Select(
c =>
new
{
CatId = c.Id,
CatName = c.Title,
OurServices = c.OurServices
.Select(
o =>
new
{
ServId = o.Id,
ServName = o.Title
}
)
}
)).ToList();
return query;
}
Linq :
from c in OurServiceCategories
where c.Language == "fa-IR"
select new
{
CatId = c.Id,
CatName = c.Title,
OurServices = from o in c.CategoryOurServices
select new
{
ServId = o.Id,
ServName = o.Title
}
}
and Result :
http://i.stack.imgur.com/dll0l.jpg
Now : I don't know how to use this,how to read by Foreach?
I want to Read like this:
var ds = OurServiceService.GetMasterDetailsFilterLang(_LangSar);
foreach (var d in ds)
{
//Read Master example : d.Id,d.Title
//do something
foreach (var details in d)
{
//Read Details example : details.Id,details.Name
//do something
}
}
foreach (var details in d.OurService) <--- don't Show .OurService
this is my Problem :
http://i.stack.imgur.com/CQOtJ.jpg
i want to show result in html code like this ( with StringBuilder ):
<ul class="container">
<li class="col-md-2">
<h4>Master.Title(1)</h4>
<ul>
<li>Details.Title(1)</li>
<li>Details.Title(2)</li>
<li>Details.Title(3)</li>
</ul>
</li>
<li class="col-md-2">
<h4>Master.Title(2)</h4>
<ul>
<li>Details.Title(1)</li>
<li>Details.Title(2)</li>
</ul>
</li>
</ul>
</ul>
Do you mean something like this ? :
var ds = from c in OurServiceCategories
where c.Language == "fa-IR"
select new
{
CatId = c.Id,
CatName = c.Title,
OurServices = from o in c.CategoryOurServices
select new
{
ServId = o.Id,
ServName = o.Title
}
};
foreach (var d in ds)
{
//here you can access d.CatId & d.CatName
foreach (var details in d.OurServices)
{
//here you can access details.ServId & details.ServName
}
}
Related
Attempting to return the below 2 lists into something I can then query against.
var people = (from c in _context.FollowingPeople
select new Models.Following.FollowingModel
{
Id = c.Id,
MediaTypeId = c.MediaTypeId,
Title = c.Title,
ClientId = c.ClientId,
Person = (from p in _context.SocialMediaPeople
where p.Id == c.SocialMediaId
select new Models.SocialMediaPeople
{
Id = p.Id,
Photo = p.Photo
}).FirstOrDefault()
});
var generic = (from c in _context.FollowingGeneric
select new Models.Following.FollowingModel
{
Id = c.Id,
MediaTypeId = c.MediaTypeId,
Title = c.Title,
ClientId = c.ClientId,
Person = null
});
var temp = people.Concat(generic).ToList();
//var data = temp.AsQueryable();
if (!string.IsNullOrEmpty(filter))
{
data = data.Where(filter);
}
data = data.Where(x => x.ClientId == ClientId);
return await data
.GetPaged(page, pageSize);
I have tried join, concat, even Zip but it results in various errors such as
(Unable to translate set operation after client projection has been applied. Consider moving the set operation before the last 'Select' call.)
So I finally got this working, the trick is to not perform any queries on the data until AFTER the concat. Th below works...
var queryA =
from c in _context.Set<FollowingPeople>()
select new Models.Following.FollowingModel
{
Id = c.Id,
MediaTypeId = c.MediaTypeId,
Title = c.Title,
ClientId = c.ClientId
};
var queryB =
from c in _context.Set<FollowingGeneric>()
select new Models.Following.FollowingModel
{
Id = c.Id,
MediaTypeId = c.MediaTypeId,
Title = c.Title,
ClientId = c.ClientId
};
var queryC =
from c in _context.Set<FollowingPublication>()
select new Models.Following.FollowingModel
{
Id = c.Id,
MediaTypeId = c.MediaTypeId,
Title = c.Title,
ClientId = c.ClientId
};
var data = (from v in queryA.Union(queryB).Union(queryC)
select new Models.Following.FollowingModel
{
Id = v.Id,
MediaTypeId = v.MediaTypeId,
Title = v.Title,
ClientId = v.ClientId,
})
.AsNoTracking()
.AsQueryable();
data = data.Where(x => x.ClientId == ClientId);
return await data.GetPaged(page, pageSize);
I need a filter between two entity.
Have two tables 1.User 2.Product
Product map with the User table.
I am going to create a dynamic where filter.
I need to find out all the users which have 'test' product.
Conditions: if userFilter count is 0 then I need all test product with the respected user.
If userFilter is there and productFilter is there then below code is working but if userFilter is not there and productFilter is there then it returning 0 row. How can I find the users which have test product? ?
Here is my Code.
public IHttpActionResult GetFilter()
{
var userFilters = new List<Filter>()
{
new Filter { PropertyName = "Username" ,
Operation = Op .Equals, Value = "Karan" },
};
var productfilter = new List<Filter>()
{
new Filter { PropertyName = "Name" ,
Operation = Op .Equals, Value = "Test product" }
};
Func<User, bool> deleg = x => true;
Func<Product, bool> delegProduct = x => true;
if (userFilters.Count > 0)
{
deleg = ExpressionBuilder.GetExpression<User>(userFilters).Compile();
}
if (productfilter.Count > 0)
{
delegProduct = ExpressionBuilder.GetExpression<Product>(productfilter).Compile();
}
var resultt = _localmarketEntities.Users.Where(deleg)
.Select(x => new
{
x.Id,
x.Username,
Product = x.Products.Where(delegProduct).Select(y => new
{
y.Id,
y.Name
}).ToList()
})
.ToList();
return Ok(resultt);
}
if i understand correct, you need all users that have test product when userFiler count is 0.
List<User> res;
var user = _localmarketEntities.Users.Where(deleg).ToList();
if (user.Count == 0) {
res = _localmarketEntities.Products.Where(delegProduct).Select(q => new User() {
Id = q.Id,
Username = q.Username,
Product = q
}).ToList();
}
else {
res = _localmarketEntities.Users.Where(deleg)
.Select(x => new
{
x.Id,
x.Username,
Product = x.Products.Where(delegProduct).Select(y => new
{
y.Id,
y.Name
}).ToList()
})
.ToList();
}
I have something like this which is getting string categories (from dropdown).
I am taking all list in catList and comparing that item in string[]categories and if it is null add this to newCategories for add to database. And lastly i want to return List<Category> with categories values.
public List<Category> ExistingCategories(string[] categories)
{
var catList = GetAllCategories().ToList();
List<Category> newCategories = new List<Category>();
var existedCategory = catList.ToLookup(x=>x.Name , v=>v.Name);
foreach (var item in categories)
{
var lookUpExistedCategory = existedCategory[item];
if (lookUpExistedCategory != )
{
newCategories.Add(new Category { Name = item });
}
}
CreateCategories(newList);
return GetAllCategories().ToList();
}
How should I do that?
You can use .Contains(TKey value)
So you can replace your foreach loop by
var newCategories = categories
.Where(m => !existedCategory.Contains(m))
.Select(m => new Category{Name = m}).toList()
By the way, I don't see the need of a LookUp<TKey, TValue>, you could use a HashSet<T>
var existedCategory = new HashSet(GetAllCategories().Select(x => x.Name).ToList());
So your method would be
public List<Category> ExistingCategories(string[] categories)
{
var existingCategories = new HashSet(GetAllCategories().Select(x => x.Name).ToList());
var newCategories = categories
.Where(m => !existingCategories .Contains(m))
.Select(m => new Category{Name = m}).toList());
//assuming this method will add and save to your db
CreateCategories(newCategories);
return GetAllCategories().ToList();
}
I wanted to create a tree view using MVC3 control toolkit and bind the data from the database dynamically to the recursive list.
Step 1: Get the details from the db to the obj like List or ArrayList
Step 2: Assign the List to viewdata in controller Action Result like
viewdata["name"]=List;
Step 3: Assign the viewdata to another List in cshtml treeview
ArrayList col = (ArrayList)ViewData["name"];
#if (col != null)
{
Html.Telerik().TreeView()
.Name("HierarchyTreeView")
.Items(items =>
{
for (int i = 0; i < col.Count; i++)
{
items.Add()
.Text(col[i].ToString())
.Value().Selected(True)
.Items((subItem) =>
{
subItem.Add()
.Text(Child.ToString()) //Here place child value
.Value();
});
}
}).ClientEvents(events => events
.OnSelect("onSelect")
).Render();
}
Step 4: Using the List assign the value to the tree view nodes using nested for loop
Step 5: Write onselect client event and get the selected value from Javascript and assign it to the javascript method of Grid filter.
function onSelect(e) {
var HNKey = treeView().getItemValue(e.item);
var HNText = treeView().getItemText(e.item);
}
Hope this will give some idea to start your process then from this you can ask questions.
I finally found better solution for this question..
I used jquery to create the tree which was much helpful for me.
After seaching for long time, I found something like this:
public class TreeView
{
public static List<Model> GetAllCategories()
{
string query="select * from tableName";
string connString = "connectionString";
var itemList = new List<Model>();
using (var con = new SqlConnection(connString))
{
using (var cmd = new SqlCommand(qry, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//added my code here to get the data..
itemList.Add(
new Model(){
categoryId= reader.GetInt32(reader.GetOrdinal("categoryId"))
)};
}
}
}
}
return itemList;
}
}
In the controller I wrote my code as:
public ActionResult Index()
{
List<Model> itemList= new List<Model>();
itemList = TreeView.GetAllCategories();
var president = itemList.
Where(x => x.Model.PAId == 0).ToList(); //
foreach (var item in president)
{
SetChildren(item, itemList);
}
return View(president);
}
private void SetChildren(Model model, List<Model> itemList)
{
var childs = itemList.
Where(x => (x.Model.PAId == model.categoryId)).ToList();
if (childs.Count > 0)
{
foreach (var child in childs)
{
SetChildren(child, itemListList);
model.Categories.Add(child);
}
}
}
Index.cshtml :
<div id="divtree">
#foreach (var item in Model)
{
<ul id="tree" >
<li>
#Html.ActionLink(item.Model.categoryName, "Action")
#Html.Partial("Childrens", item)
</li>
</ul>
}
</div>
<script type="text/javascript">
$(function () {
$('#treeViewContent').load('#Url.Action("CreateCategory","Category")');
$('#divtree').jstree({
"plugins": ["themes", "html_data", "ui", "cookies"]
})
.bind('loaded.jstree', function () {
$(this).jstree('open_all');
});
});
</script>
Childrens.cshtml:
#foreach (var item in Model.Categories)
{
<ul>
#if (item != null)
{
<li>
#Html.ActionLink(item.Model.categoryName, "Action")
#if (item.Categories.Count > 0)
{
#Html.Partial("Childrens", item)
}
</li>
}
</ul>
}
and finally got tree like this:
I have a list of objects, those objects may or may not have contact info:
// Join contact
query = query.Join(
(new ContactRepository(this.Db)).List().Where(x => x.IsMainContact),
x => new { x.ListItem.ContentObject.LoginId },
y => new { y.LoginId },
(x, y) => new ListItemExtended<ListItemFirm>
{
City = y.City,
State = y.State,
Country = y.Country
});
This does inner join on 'LoginId'. But I need an outter join so that if contact info does not exists for a given LoginId it will be empty.
Please help
thanks
You should execute outer join manually:
var contacts = (new ContactRepository(this.Db)).List();
query.Select(item =>
{
var foundContact = contacts.FirstOrDefault(contact => contact.Id == item.Id);
return new ListItemExtended<ListItemFirm>()
{
Id = item.Id,
City = foundContact != null ? foundContact.City : null,
State = foundContact != null ? foundContact.State : null,
Country = foundContact != null ? foundContact.Country : null,
};
})
But remember that if your Contact item is struct - checking for null isn't proper way. Use Any() operator instead of FirstOrDefault().