我有以下数据库表:
# account_type table #
id desc
----------------
1 savings
2 checking
# account table #
id account_type_id Name
--------------------------
1 2 Don
2 1 Henry
3 1 Lisa
4 2 Jenifer
我想写一个linq查询,这样它返回一个包含集合的对象,即
desc: Savings { Don, Jenifer }
我创建了这些类:
public class acctType
{
public id { get; set; }
public string desc { get; set; }
public IEnumerable<account> account{ get; set;}
}
public class account
{
public int id { get; set; }
public int account_type_id { get; set; }
public string name { get; set;}
}
我的方法在api中调用:
public accType Get(int id)
{
var accounts = (from c in db.account_type
where c.p_id == id
select new accType
{
id = c.id,
name = c.desc,
account = new List<account> { name = c.desc }
});
}
return accounts.FirstOrDefault()
问题是,当我得到帐户对象返回时,它只有一个名称,即
dsc: checking { Don }
答案应该是Don和jennifer。我该如何解决这个问题?
您只返回FirstOrDefault()项,将返回语句更改为
return accounts.ToList()
编辑:public List<accType> Get(int id)
{
var accounts = (from c in db.account_type
where c.p_id == id
select new accType
{
id = c.id,
name = c.desc,
account = new List<account>()
{
name=c.desc
}
});
return accounts.ToList()
}