Reputation: 89
We have recently changed the implementation from ADO.NET to Repository Pattern and generated entities using Entity Framework.
Now I am trying to access 2 tables(Accounts and Submission) and I am not getting Include method to access second table. TO access Single table, SelectAll Method is giving all required data. WOndering what am i doing wrong here?
Appreciate your responses.
Here is my Code:
public class GPController : ApiController
{
private readonly IRepository<Account> _acctRepository;
private readonly IRepository<Submission> _subRepository;
public GPController(IRepository<Account> acctRepository, IRepository<Submission> subRepository)
{
_acctRepository = acctRepository;
_subRepository = subRepository;
}
[HttpPost]
public IHttpActionResult CreateAccount( Account account)
{
try
{
_acctRepository.Insert(account);
_acctRepository.Save();
return Ok<bool>(true);
}
catch (Exception ex)
{
throw ex;
}
}
[HttpPost]
public IHttpActionResult CreateSubmission(Submission submission)
{
try
{
_subRepository.SelectAll().ToList();
_subRepository.Save();
return Ok<bool>(true);
}
catch (Exception ex)
{
throw ex;
}
}
[HttpGet]
public IHttpActionResult GetAccountTreeDetails()
{
try
{
var accounts = _acctRepository.SelectAll().ToList();
var submissions = _subRepository.SelectAll().ToList();
//if (submissions.Any())
//{
// var data = from a in accounts
// left join s in submissions on a.AccountId equals s.AccountId
// select a;
//}
//var data = from acct in _acctRepository
// join sub in _subRepository on acct.AccountId equals sub.AccountId
// select acct;
return Ok<List<Account>>(result);
}
catch (Exception ex)
{
throw ex;
}
}
}
Here AccountTable is the Primary table that has AccountID. WhereAs Submission Table has AccountID that is Foreign Keyed from Account Table.
Upvotes: 0
Views: 1689
Reputation: 440
Your SelectAll() should be something like this:
var accounts = _acctRepository.SelectAll().Include(a=> a.Submissions).ToList();
Make sure that SelectAll() returns a queryable. Secondly, your models should have navigation properties, like below:
public class Account
{
public virtual ICollection<Submission> Submissions { get; set; }
}
public class Submission
{
public virtual Account Account { get; set; }
}
Upvotes: 1