我无法在Entity框架中执行Raw Sql Where查询。
型号:
public partial class Web_User_Setup_Header
{
public byte[] timestamp { get; set; }
public string User_ID { get; set; }
public bool Enable { get; set; }
public System.DateTime Expiration_Date { get; set; }
}
Fluent Model Entity Configuraiton:
public class Web_User_Setup_HeaderConfigruation : EntityTypeConfiguration<Web_User_Setup_Header>
{
public Web_User_Setup_HeaderConfigruation()
{
ToTable("Web User Setup Header");
HasKey(x => x.User_ID).Property(x => x.User_ID).HasColumnName("User ID");
Property(x => x.Expiration_Date).HasColumnName("Expiration Date");
}
}
我正在执行的Sql查询是:
Web_User_Setup_Header WebSetup = context.Web_User_Setup_Headers.SqlQuery("Select * from [" + Convert.ToString(HttpContext.Items["Company"]) +
"$Web User Setup Header] where User_ID=@p0", uid).SingleOrDefault();
其中HttpContext.Items["Company"] = "Sachin Sales"
和uid = "web"
当我执行上述查询时,它会给出错误:Invalid column name 'User_ID'.
当我在查询中将User_ID
更改为[User ID]
时,它会将错误描述为:
The data reader is incompatible with the specified 'JSTestWeb.Models.Web_User_Setup_Header'. A member of the type, 'User_ID', does not have a corresponding column in the data reader with the same name.
有人能说清楚这件事吗?但是,数据库字段名称仅在数据库中为[User ID]
,我无法更改它。
答案 0 :(得分:0)
您可以使用ESQL构建动态查询。但是您需要使用ObjectContext
API来执行ESQL。
public class MyContextTest : DbContext
{
public virtual ObjectContext UnderlyingObjectContext
{
get
{
return ((IObjectContextAdapter)this).ObjectContext;
}
}
}
查询语法与SQL略有不同。
Web_User_Setup_Header WebSetup = context.UnderlyingObjectContext
.CreateQuery<Web_User_Setup_Header>("Select VALUE C from [" +
Convert.ToString(HttpContext.Items["Company"]) +
"$Web User Setup Header] AS C where C.[User ID]=@p0",
new ObjectParameter("p0", uid)).SingleOrDefault();