【发布时间】:2012-08-22 04:59:12
【问题描述】:
使用 MVC3 VS2010 和 SQL Server 2008 Express 我正在尝试基于两个 SQL Server 表进行过滤并显示结果。 一张表是客户表,另一张是代理表。它们在客户表中具有共同的 ClientAgentID 和在代理表中的 ID。代理记录并且应该能够看到分配给代理的客户端。如果您对执行此操作的最佳方法有任何想法,请帮助我。到目前为止,我正在尝试在客户端控制器中进行过滤,这就是我所拥有的,但我得到的消息是在标题中。
public ActionResult Index()
{
//This displays all the clients not filtered by the Agent ID number
//var clientItems = db.MVCInternetApplicationPkg;
//return View(clientItems.ToList());
//Trying to filter by the agent name given in the login page then finding
//the agent ID
var getAgentID = from a in db.AgentsPkg
where a.AgentLogin == User.Identity.Name
select a.ID;
var clientItems = from r in db.MVCInternetApplicationPkg
where Convert.ToString(r.ClientAgentID)
== Convert.ToString(getAgentID)
select r;
//THIS IS THE LINE OF CODE THAT SHOWS THE ERROR MESSAGE
return View(clientItems.ToList());
}
这是我在 Music Store 之后的第一个 MVC 项目,因此愿意学习并接受任何帮助或建议。 干杯
这是我最后使用的解决方案。如果这是一个好方法,任何反馈将不胜感激
public ActionResult Index()
{
var innerJoint = from agents in db.AgentsPkg where agents.AgentLogin == User.Identity.Name
join clients in db.MVCInternetApplicationPkg on agents.ID equals clients.ClientAgentID
select clients;
return View(innerJoint.ToList());
}
【问题讨论】:
-
AgentsPkg 和 MVCInternetApplicationPkg 之间是否定义了外键?
-
@Merenzo SQL 数据库中定义了外键,但在 MVC 中没有引用外键
-
@WillNZ 根据您的描述,我希望在您的“MVCInternetApplicationPkg”类的实体模型中生成一个“AgentsPkg”导航属性,这样您就可以只用一个来获取列表-liner(几乎:)
-
@WillNZ:您的解决方案看起来应该可以工作,但总的来说,我会利用存在的导航属性(为外键关系自动生成)来简化查询。您的“MVCInternetApplicationPkg”实体是否具有“AgentsPkg”属性?
标签: c# linq entity-framework linq-to-entities