1.解决“不允许在查询中显式构造实体类型” 问题

1.解决“NotSupportedException:“Explicit construction of entity type 'xx object' in query is not allowed.即:“不允许在查询中显式构造实体类型” 问题及 
使用其他方法实现返回List<Model对象>或者IQueryable<Model对象>对象。
方法1
例子1:
      实体类UsersInfo
     [Table(Name = "Users")]
public class UsersInfo
{
[Column(Name="UserID", IsPrimaryKey = true, CanBeNull=false, IsDbGenerated=false, AutoSync=AutoSync.OnInsert)]
public System.String UserID { get ; set ; }
		[Column(Name="CompanyName",CanBeNull=false)]
public System.String CompanyName { get ; set ; }
    }
public IQueryable<UsersInfo> GetItemsForListing(int ownerId)
{
    ItemDataContext dataContext = new ItemDataContext();
    var query = from item in dataContext.Users
                where item.UserID == ownerId
                orderby item.UserID descending
                select new UsersInfo
                {
                    UserID = item.UserID,
                    CompanyName= item.CompanyName,
                };
    return query;
}
使用上面的代码将报 “不允许在查询中显式构造实体类型” 错误,怎么解决此问题呢?
修改UsersInfo实体类
      实体类UsersInfo
	public class UsersInfo
{
public System.String UserID { get ; set ; }
		public System.String CompanyName { get ; set ; }
    }
这样就不会在报 “不允许在查询中显式构造实体类型” 错误了.

方法2:
使用DataContext对象的Translate方法
例子2:
public List<EmloyeesInfo> GetEmloyeesInfoForListing()
{
      List<EmployeesInfo> emp_list=null;
       ItemDataContext dataContext = new ItemDataContext();
       datacontext.Connection.Open();
SqlConnection con = (SqlConnection)datacontext.Connection;
string sql = @"SELECT EmployeeID,[FirstName] ,[LastName] FROM [Employees] ";
SqlCommand com = new SqlCommand(sql, con);
using (DbDataReader reader = com.ExecuteReader(CommandBehavior.CloseConnection))
{
//在ExecuteReader之后即使用Translate方法将DbDataReader里的数据转换成EmployeesInfo对象
//Translate方法从DbDataReader中生成对象的规则和内置的DataContext.ExecuteQuery方法一样
return emp_list = datacontext.Translate<EmployeesInfo>(reader).ToList();
}
       //注意:DataContext对象如果显示的将Connection打开的话,
//即使调用了DataContext对象的Dispose方法也不会自动关闭,
//所以在这里使用Using(),在关闭DbDataReader的时候将Connection也一起关闭了
}
对上面方法扩展如下:
     public static List<T> ExecuteQuery<T>(this DataContext context, IQueryable query) 
{
DbCommand com = context.GetCommand(query);
context.OpenConnection();
using(DbDataReader reader=com.ExecuteReader())
{
return context.Translate<T>(reader).ToList();
}
}
        public static void OpenConnection(this DataContext context)
{
if (context.Connection.State == ConnectionState.Closed) context.Connection.Open();
}


方法3:
使用DataContext对象的ExecuteQuery方法

例子3:

public IQueryable<EmloyeesInfo> GetEmloyeesInfoForListing(int id)
{

      ItemDataContext dataContext = new ItemDataContext();

      string sql = "SELECT EmployeeID,[FirstName] ,[LastName] FROM [Employees] where EmloyeeID={0}";
      return datacontext.ExecuteQuery<EmployeesInfo>(sql,id).AsQueryable<EmloyeesInfo>();

}

 
posted @ 2013-08-13 15:55  大脸  阅读(1701)  评论(0编辑  收藏  举报