如何使用ActionLink MVC 5执行以下sql查询?

时间:2014-12-21 06:39:14

标签: c# asp.net-mvc razor-2

是否可以单击actionlink名称并让它检索关联的记录,就像下面的sql语句一样?客户名称html链接 - >转到客户详细信息视图的索引,仅检索与客户名称(CustomerNameID)关联的记录。

SELECT dbo.CustomerName.CustomerNameName, dbo.CustomerDetail.CustomerNameID
FROM dbo.CustomerDetail INNER JOIN
     dbo.CustomerName ON dbo.CustomerDetail.CustomerNameID = dbo.Cust

型号:客户名称

 public partial class CustomerName
    {
        public CustomerName()
        {
            this.CustomerDetails = new HashSet<CustomerDetail>();
            this.CustomerEquipments = new HashSet<CustomerEquipment>();
            this.CustomerHealthChecks = new HashSet<CustomerHealthCheck>();
        }

        public int CustomerNameID { get; set; }
        public Nullable<int> CustomerHealthCheckID { get; set; }
        public Nullable<int> CustomerEquipmentID { get; set; }
        public int MasterLicNum { get; set; }
        public string CustomerNameName { get; set; }
        public Nullable<int> Active { get; set; }

        public virtual CustomerDetail CustomerDetail { get; set; }

        public virtual ICollection<CustomerDetail> CustomerDetails { get; set; }
        public virtual ICollection<CustomerEquipment> CustomerEquipments { get; set; }
        public virtual ICollection<CustomerHealthCheck> CustomerHealthChecks { get; set; }
    }
}

型号:为CustomerDetail

public partial class CustomerDetail
    {
        public CustomerDetail()
        {
            this.CustomerNotes = new HashSet<CustomerNote>();
        }

        public int CustomerDetailID { get; set; }
        public int CustomerNameID { get; set; }
        public System.DateTime DateUpdated { get; set; }
        public System.DateTime DateCreated { get; set; }
        public int CustomerPriorityID { get; set; }
        public int CustomerStatusHealthID { get; set; }
        public Nullable<int> EquipmentID { get; set; }
        public Nullable<int> CustomerHealthCheckID { get; set; }
        public int LREngineerID { get; set; }
        public int CustomerEngineerID { get; set; }
        public string Description { get; set; }
        public byte[] RowVersion { get; set; }

        public virtual CustomerEngineer CustomerEngineer { get; set; }
        public virtual CustomerName CustomerName { get; set; }
        public virtual CustomerPriority CustomerPriority { get; set; }
        public virtual CustomerStatusHealth CustomerStatusHealth { get; set; }
        public virtual LREngineer LREngineer { get; set; }
        public virtual ICollection<CustomerNote> CustomerNotes { get; set; }
    }
}

控制器:

return View(CustomerName.ToPagedList(pageNumber, pageSize));

查看:

@Html.ActionLink(item.CustomerNameName.ToString(), "Index", "CustomerDetail", new {ID = item.CustomerNameID }, null)

路线:

 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "CustomerName", action = "Index", id = UrlParameter.Optional }

我重建了我的控制器来清理它。它是目前标准的开箱即用控制器。 CustomerNameController Index():

// GET: CustomerName
public async Task<ActionResult> Index(int? CustomerNameID = null)
{
    return View(await db.CustomerNames.ToListAsync());
}

// GET: CustomerName/Details/5
public async Task<ActionResult> Details(int? id)
{
    if (id == null)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
    CustomerName customerName = await db.CustomerNames.FindAsync(id);
    if (customerName == null)
    {
        return HttpNotFound();
    }
    return View(customerName);
}

CustomerDetailController Index():

  public async Task<ActionResult> Index(string sortOrder, string currentFilter, string searchString, int? page)
        {
            var customerDetails = db.CustomerDetails.Include(c => c.CustomerEngineer).Include(c => c.CustomerName).Include(c => c.CustomerPriority).Include(c => c.CustomerStatusHealth).Include(c => c.LREngineer);
            ViewBag.CurrentSort = sortOrder;
            ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
            ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;
             var CustomerDetails = from s in db.CustomerDetails
                           select s;
            if (!String.IsNullOrEmpty(searchString))
            {
                CustomerDetails = CustomerDetails.Where(s => s.Description.Contains(searchString));
            }
            switch (sortOrder)
           {
                case "name_desc":
                    CustomerDetails = CustomerDetails.OrderByDescending(s => s.CustomerNameID);
                    break;
                case "Date":
                    CustomerDetails = CustomerDetails.OrderBy(s => s.DateUpdated);
                    break;
                case "date_desc":
                    CustomerDetails = CustomerDetails.OrderByDescending(s => s.DateUpdated);
                    break;
                default:  // Name ascending 
                    CustomerDetails = CustomerDetails.OrderBy(s => s.CustomerNameID);
                    break;
            }

            int pageSize = 15;
            int pageNumber = (page ?? 1);

            //return View(await customerDetails.ToListAsync());
            return View(CustomerDetails.ToPagedList(pageNumber, pageSize));
        }

任何帮助将不胜感激。这甚至可能吗?

2 个答案:

答案 0 :(得分:0)

答案很简单,但我没理解。多次运行程序后,我注意到客户名称/索引ID已被传递但是CustomerDetail / Index未能将其取出并过滤结果。我添加了以下代码,它终于奏效了。谢谢大家的帮助。

        // GET: CustomerDetail
    public async Task<ActionResult> Index(int CustomerNameID)
    {

        IQueryable<CustomerDetail> CustomerDetail = db.CustomerDetails
           .Where(c => c.CustomerNameID == CustomerNameID)
           .OrderBy(d => d.CustomerNameID)
           .Include(d => d.CustomerName);


        return View(await CustomerDetail.ToListAsync());
    }

答案 1 :(得分:-1)

修改

SELECT dbo.CustomerName.CustomerNameName, dbo.CustomerDetail.CustomerNameID
FROM dbo.CustomerDetail INNER JOIN
     dbo.CustomerName ON dbo.CustomerDetail.CustomerNameID = dbo.Cust

在LINQ中:

var query = from detail in CustomerDetails
            //from name in CustomerNames.Where(r=>r.CustomerDetail == detail)
            from name in CustomerNames.Where(r=>r.CustomerNameID == detail.CustomerNameID)
            select new {CustomerName = name.CustomerName, CustomerNameId = detail.CustomerNameId}

关闭

如果要在同一页面上显示详细信息,请修改Index操作。创建一个包含客户列表和详细信息对象的模型。

检查输入参数是否为空,如果是,则仅返回客户列表。如果参数不为null,则返回客户列表,其中包含客户详细信息。

public ViewResult Index(int? customerId = null)
{
    if(cusomerId == null)
    {
        return new IndexModel {Customers = customersList};
    }
    else
    {
        return new IndexModel {Customers = customersList, Details = getDetailsById(customerId)};
    }
}

模型示例:

public class IndexModel
{
    public List<Customer> Customers {get;set;}
    public CustomerDetails Details {get;set;}
}

ActionLink的:

@Html.ActionLink(item.CustomerNameName.ToString(), "Index", "CustomerDetail", new {customerId = item.CustomerNameID }, null)