0

我无法在实体框架中执行 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; }
}

流利的模型实体配置:

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]仅在数据库中,我无法更改。

4

1 回答 1

0

您可以使用ESQL构建动态查询。但是您将需要使用ObjectContextAPI 来执行 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();
于 2012-04-13T06:46:45.037 回答