如何通过两种单独的控制器方法访问单个数据库查询的结果

时间:2019-01-26 20:36:59

标签: c# asp.net-mvc entity-framework

我实现了对网站的搜索。它有两个主要的实体组:客户和企业。它们可以彼此连接,并且我都在两个属性中都搜索字符串。

对控制器的调用从两个单独的ajax函数到两个单独的动作,结果通过JSON结果放入数据表中。

我只想运行这两行:

var clients = GetClientsBySearchString(searchString, practiceId);
var businesses = GetBusinessesBySearchString(searchString, practiceId);

实现此目标的最佳方法是什么?

这是我的控制人 SearchResultsController.cs

public class SearchResultsController : Controller
    {

        private readonly IUnitOfWork _unitOfWork;

        public SearchResultsController(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public ActionResult Index(string searchString)
        {
            ViewBag.SearchString = searchString;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SearchBusinesses(string searchString)
        {
            if (String.IsNullOrEmpty(searchString))
                return new EmptyResult();

            var practiceId = _unitOfWork.Users.GetPracticeIdForUser(User.Identity.GetUserId());
            var result = Json(_unitOfWork.SearchResults.GetBusinessesSearchResults(searchString, practiceId)
                .Select(Mapper.Map<Business, BusinessDto>));
            result.MaxJsonLength = int.MaxValue;
            return result;
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult SearchClients(string searchString)
        {
            if (String.IsNullOrEmpty(searchString))
                return new EmptyResult();

            var practiceId = _unitOfWork.Users.GetPracticeIdForUser(User.Identity.GetUserId());
            var result = Json(_unitOfWork.SearchResults.GetClientsSearchResults(searchString, practiceId)
                .Select(Mapper.Map<Client, ClientDto>));
            result.MaxJsonLength = int.MaxValue;
            return result;
        }
    }

这是 Index.cshtml 中的脚本:

@section scripts
{
    <script>
        $(document).ready(function () {

            function getToken() {
                return $("[name='__RequestVerificationToken']").attr('value');
            }

            var tableClients = $('#clients').DataTable({
                ajax: {
                    url: '/searchresults/searchclients?searchString=' + $('#search-results').attr('data-search-string'),
                    dataSrc: '',
                    deferRender: true,
                    method: 'POST',
                    data: { __RequestVerificationToken: getToken() },
                },
                columns: [
                    {
                        data: 'Reference'
                    },
                    {                        
                        data: 'Name',
                        render: function (data, type, client) {
                            return '<a href="/clients/clients/details/' + client.Id + '">' + client.Surname + ' ' + client.FirstName + '</a>';
                        }
                    },
                    {
                        data: 'Email',
                        render: function (data, type, client) {
                            return '<a href="mailto:' + client.Email + '">' + client.Email + '</a>';
                        }
                    }                     
                ]
            });                   

            var tableBusinesses = $('#businesses').DataTable({
                ajax: {
                    url: '/searchresults/searchbusinesses?searchString=' + $('#search-results').attr('data-search-string'),
                    dataSrc: '',
                    method: 'POST',
                    data: { __RequestVerificationToken: getToken() },
                },
                columns: [
                    {
                        data: 'Reference'
                    },
                    {                        
                        data: 'Name',
                        render: function (data, type, business) {
                            return '<a href="/businesses/businesses/details/' + business.Id + '">' + business.Name + '</a>';
                        }
                    }
                ]
            });                   
        });
    </script>
}

最后是存储库 SearchResultRepository.cs

 public class SearchResultRepository : ISearchResultRepository
    {
        private readonly ElmboardDbContext _context;

        public SearchResultRepository(ElmboardDbContext context)
        {

            _context = context;

        }

        private IQueryable<Business> GetBusinessesBySearchString(string searchString, int practiceId)
        {
            return _context.Businesses.Where(b => [...].Contains(searchString)));
        }

        private IQueryable<Client> GetClientsBySearchString(string searchString, int practiceId)
        {
            return _context.Clients.Where(c => [...].Contains(searchString)));

        }

        public IEnumerable<Business> GetBusinessesSearchResults(string searchString, int practiceId)
        {
            var clients = GetClientsBySearchString(searchString, practiceId);
            var businesses = GetBusinessesBySearchString(searchString, practiceId);

            var relatedBusinesses =
                from c in clients
                join cbr in _context.ClientBusinessRelationships on c.Id equals cbr.ClientId
                join b in _context.Businesses on cbr.BusinessId equals b.Id
                select b;

            return businesses.Union(relatedBusinesses);
        }

        public IEnumerable<Client> GetClientsSearchResults(string searchString, int practiceId)
        {
            var clients = GetClientsBySearchString(searchString, practiceId);
            var businesses = GetBusinessesBySearchString(searchString, practiceId);

            var relatedClientsByClient =
                from c1 in clients
                join ccr in _context.Client1Client2Relationships on c1.Id equals ccr.Client1Id
                join c2 in _context.Clients on ccr.Client2Id equals c2.Id                
                select c2;

            var relatedClientsByBusiness =
                from b in businesses
                join cbr in _context.ClientBusinessRelationships on b.Id equals cbr.BusinessId
                join c in _context.Clients on cbr.ClientId equals c.Id
                select c;

            return clients.Union(relatedClientsByClient).Union(relatedClientsByBusiness);
        }

0 个答案:

没有答案