再次用外键返回实体MVC [英] MVC returning entity with foreign key, again
问题描述
代码是:
public async任务< PagedResults< ItemType>> GetAsync(int skip = 0,int take = -1)
{
PagedResults< ItemType> pagedResults;
try
{
IQueryable< ItemType> query = _dbSet.Include(IndicatorDetails);
query = take == -1
? query.OrderBy(i => i.IndicatorDetails.Code)
:query.OrderBy(i => i.IndicatorDetails.Code);
var data = await query.ToListAsync();
pagedResults = new PagedResults< ItemType>(data,skip,take,data.Count);
}
catch(异常e)
{
抛出新异常(string.Format(无法从数据库获取项目类型{0},e.Message) E);
}
return pagedResults;
}
我可以让它工作,只是返回一行,因为我' m传递一个id,我可以在ItemType和IndicatorType类之间匹配,但我无法弄清楚如何使_dbSet包含IndicatorDetails。
感谢
您可以随时通过加入表
exemple( j1 是您的 ItemType , j2 是您的 IndicatorType )
code> ViewBag.listItems = ItemType.Join(IndicatorType,j1 => j1.key,j2 => j2.key2,(j1,j2)=> new {j1,j2})AsEnumerable() 。选择(v => new SelectListItem(){Value = t.t1.userid.ToString(),Text = string.Format({0} {1},t.t1.firstName,t.t2.lastName )});
鉴于您可以通过 ViewBag.listItems
@ Html.DropDownListFor(m => m.userid,new SelectList(ViewBag.listItems,Value,Text, - Sélections- ),新的{@class =form-control}
I'm trying to return an entity that has a foreign key and I'm a bit stuck. Trying to populate a dropDownList with the results of two tables. There's a foreign key relationship between the ItemType and IndicatorType tables.
Code is:
public async Task<PagedResults<ItemType>> GetAsync(int skip = 0, int take = -1)
{
PagedResults<ItemType> pagedResults;
try
{
IQueryable<ItemType> query = _dbSet.Include("IndicatorDetails");
query = take == -1
? query.OrderBy(i => i.IndicatorDetails.Code)
: query.OrderBy(i => i.IndicatorDetails.Code);
var data = await query.ToListAsync();
pagedResults = new PagedResults<ItemType>(data, skip, take, data.Count);
}
catch (Exception e)
{
throw new Exception(string.Format("Could not get item types from database. {0}", e.Message), e);
}
return pagedResults;
}
I can get it to work for just returning a single row, because I'm passing in an id that I can match between ItemType and IndicatorType classes but I can't figure out how to get the _dbSet to do the include the IndicatorDetails.
Thanks in advance.
you can always do the query by joining both table exemple (j1 is your ItemType and j2 is your IndicatorType)
ViewBag.listItems = ItemType.Join(IndicatorType, j1 => j1.key, j2 => j2.key2, (j1, j2) => new {j1, j2}).AsEnumerable().Select( v => new SelectListItem() { Value = t.t1.userid.ToString(), Text = string.Format("{0} {1}", t.t1.firstName, t.t2.lastName) });
in view you can pass ViewBag.listItems
@Html.DropDownListFor(m => m.userid, new SelectList(ViewBag.listItems,"Value","Text","-Sélections-"), new { @class ="form-control"})
这篇关于再次用外键返回实体MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!