我正在使用Entity Framework执行此简单查询
db.Database.SqlQuery<string>("SELECT * FROM hospital");
但我收到了这个错误:
数据阅读器有多个字段。多个字段对EDM原语或枚举类型无效。
可能是什么问题?
答案 0 :(得分:35)
查看医院餐桌的样子会很有用,但假设医院由HospitalId和HospitalName组成,那么您有几个选择。
db.Database.SqlQuery<IEnumerable<string>>("SELECT hospitalName FROM hospital"); //would work if all you're trying to do is get the Name
db.Database.SqlQuery<MyEntity>("SELECT * FROM hospital"); //where you define MyEntity as the same structure as the table would work
db.Database.SqlQuery<IEnumerable<Tuple<int, string>>>("SELECT * FROM hospital"); // would theoretically work although I haven't tried it. Where the Tuple items would have to match the database types in order. I.e. if field 1 is an int and field 2 is a string then Tuple<int,string>
基本上错误是代码不知道怎么把医院的结构塞进一个字符串
答案 1 :(得分:6)
这解决了我的问题,一些结果没有得到应有的方式
string storedProcedure = "Admin_AutoGenerateKeywordsFortblCompany @Company_ID=" + CompId;
var s= db.ExecuteStoreQuery<List<string>>("exec " + storedProcedure).ToList();
这里可以捕获单个或多个结果
答案 2 :(得分:4)
如果您尝试执行INSERT
,UPATE
或DELETE
命令
而不是使用SqlQuery
使用ExecuteSqlCommand
using (var ctx = new SchoolDBEntities())
{
int noOfRowUpdated = ctx.Database.ExecuteSqlCommand("Update student
set studentname ='changed student by command' where studentid=1");
int noOfRowInserted = ctx.Database.ExecuteSqlCommand("insert into student(studentname)
values('New Student')");
int noOfRowDeleted = ctx.Database.ExecuteSqlCommand("delete from student
where studentid=1");
}
详情请访问 - http://www.entityframeworktutorial.net/EntityFramework4.3/raw-sql-query-in-entity-framework.aspx
答案 3 :(得分:0)
根据 cgotberg 给我的敏感答案,我将回答我自己的问题。 该代码的问题是某些表的字段与数据库中的字段不同(我正在寻找异常,但我找不到它,对不起),但实际上存在。 出于某种原因,我不得不将表的所有字段添加到查询字符串中。我的意思是,我必须写“SELECT hospital_phone,holpital_street等等来自医院”,如果我写“SELECT hospital_name 来自医院”,则会发生异常。
希望我能解释清楚。