存储库模式访问多个表?

时间:2017-05-22 01:54:03

标签: c# entity-framework linq linq-to-entities repository

我们最近将实现从ADO.NET更改为Repository Pattern并使用Entity Framework生成实体。

现在我正在尝试访问2个表(帐户和提交),而我没有使用Include方法访问第二个表。 要访问单个表,SelectAll方法将提供所有必需的数据。在这里弄错我在做什么?

感谢您的回复。

这是我的代码:

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;
            }
        }
    }

此处AccountTable是具有AccountID的主表。 WhereAs提交表的AccountID是来自帐户表的外键。

以下是帐户表: enter image description here

以下是提交表: enter image description here

1 个答案:

答案 0 :(得分:1)

你的SelectAll()应该是这样的:

var accounts = _acctRepository.SelectAll().Include(a=> a.Submissions).ToList();

确保SelectAll()返回可查询的内容。 其次,您的模型应具有导航属性,如下所示:

public class Account
    {
        public virtual ICollection<Submission> Submissions { get; set; }
    }

public class Submission
{
    public virtual Account Account { get; set; }
}