使用MVC3 VS2010和SQL Server 2008 Express 我试图基于两个SQL Server表进行筛选并显示结果。 一个表是客户表,另一个表是代理。它们在clients表中具有共同的ClientAgentID,在Agents表中具有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());
}
这是我在音乐商店之后的第一个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());
}
答案 0 :(得分:3)
你不想在你的linq语句中使用转换!!!!!!
string clientagentid=Convert.ToString(r.ClientAgentID);
string getagentid= Convert.ToString(getAgentID);
var clientItems = (from r in db.MVCInternetApplicationPkg
where clientagentid==getagentid
select r).ToList();
return View(clientItems);
答案 1 :(得分:2)
<强> 1。错误原因:
正如其他人所说,这是由于在Convert.ToString()
子句中使用where
,Linq无法将其转换为SQL。我希望您的原始查询只需删除两个Convert.ToString()
函数即可。
<强> 2。 “......这样做的最佳方式”:
嗯,更好的方式....:)
在实体框架中,通过Navigation Properties在相关实体之间导航的简便方法。如果您的方法是“数据库优先”,则应在EDMX中为您生成这些方法。如果你的方法是“Code First”,那么有一篇很好的帖子here描述了如何设置它。
无论哪种方式,我希望你的Client
类具有Agent
的导航属性(即类似于你提到的MvcMusicStore示例中的OrderDetail的Order
属性):
public virtual Agents Agent { get; set; }
然后你的方法变得非常简单(即类似于MvcMusicStore中的许多控制器方法)......没有Joins
或需要多个语句:
var clients = db.MVCInternetApplicationPkg.Where(c => c.Agent.AgentLogin == User.Identity.Name);
return View(clients.ToList());
答案 2 :(得分:2)
答案是使用 SqlFunctions.StringConvert (使用'decimal'或'double'但'int'不起作用)参见示例
using System.Data.Objects.SqlClient ;
var clientItems = from r in db.MVCInternetApplicationPkg
where SqlFunctions.StringConvert((double ), r.ClientAgentID)
== SqlFunctions.StringConvert((decimal) , getAgentID)
select r;
请参阅http://msdn.microsoft.com/en-us/library/dd466166.aspx了解详情。
答案 3 :(得分:1)
Linq提供程序(Linq to Entities)正在尝试将您的查询转换为SQL,并且没有Convert的映射。这些错误有时难以破译,但线索在“String.ToString()”行中。还要意识到,由于延迟执行,在clientItems
被迭代之前不会显示错误,在toList()
return View(clientItems.ToList());
的情况下
答案 4 :(得分:0)
LINQ无法将Convert.ToInt32()映射到等效的T-SQL中,因此它会抛出异常。正如COLD TOLD所说,您必须转换该值,然后在查询中使用转换后的值。
请检查:Why do LINQ to Entities does not recognize certain Methods?