开发者

Listing data from 3 different but associated table into one dropdown (using linq-to-sql and mvc3)

开发者 https://www.devze.com 2023-04-06 18:27 出处:网络
i ve 3 tables in my database : item,group,groupdetail; in table item there are 2 fields : id,item_name (bigint\"long\",string)

i ve 3 tables in my database : item,group,groupdetail;

in table item there are 2 fields : id,item_name (bigint"long",string)

in table group there are 2 fields : id,group_name (bigint,string)

in table group_details开发者_JAVA技巧 there are 3 fields : id,group_id,item_id (bigint,bigint,bigint)

group_id is nullable cause some items have no groups.

what i want to do is listing the names of groups where the items that has a group "group_name" ordered by item_id and also in the same list i wanna show the item names which has no group and both of them should be ordered by item_id

i can also fill dropdowns with jquery if required for this action but i'm brain freezed with listing part.

controller

 var data = from guru in dataContext.group_details select guru;

 var itemsWithoutGroup = data.Where(c => c.group_id == null).OrderBy(c => c.item_id).Where(c => c.item_id == c.item.id).Select( c=>c.item.item_name);

 var groups = data.Where(c => c.group_id != null).OrderBy(c => c.item_id).Where(c => c.group_id  == c.group.id).Select( c=>c.group.group_name);

 var grandlist = // i wanna do smt here to list both in one dropdown ordered by item_id

view

@Html.DropDownList("GroupDetails", new SelectList((System.Collections.IEnumerable)ViewData["GroupDetailedList"], "id", "item_id"))

EDIT:

To be more specific about it..

Group-1 
Group-2
Item-9
Group-3
Item-15
Group-4

So this is how the dropdown should look like! Items with no groups should be listed too with the item groups and be ordered by item_id..


The statement i would use is:

var groupswithItems = (from groupdetail in group_details select groupdetail.group_id
                     join group in groups groupdetail.group_id equals group.id
                     orderby groupdetail.item_id
                     select new SelectListItem {Text= group.name, Value= group.id.ToString() }).ToList()

var itemswithotgroups = (from item in items orderby item.id select new SelectListItem { Text= item.name, Value= item.id.ToString() }).ToList()

ViewBag.Combined = groupswithItems.union(itemswithotgroups);

This would give you the list from all groups that are in group detail (those contain items i presume) and convert it to object that Dropdownlist can handle

@Html.DropDownList("GroupDetails", ViewBag.groups as List<SelectListItem>))
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号