计算行数和存储值

Counting rows and storing value

我一直在尝试在变量中存储一个值,这取决于从数据库返回的值。 本质上,我希望它根据房间类型计算有多少房间,并将其存储在一个变量中以供其他地方使用。

我有的是:

                DLDbContext context = new DLDbContext();
            //Counts how many versions of that room exists
            int RoomTypes = (from u in context.Room where u.type == ddlRoomType.SelectedItem.ToString() select u).Count();

出现的错误是:

Unable to create a constant value of type 'System.Web.UI.WebControls.ListItem'. Only primitive types or enumeration types are supported in this context.

ddlRoomType 是一个下拉列表,用户可以在其中选择房间类型,并根据他们的选择,通过数据库搜索实际存在的房间数量。

这是因为您在这一行隐含地使用了 LINQ to Entities:

(from u in context.Room where u.type == ddlRoomType.SelectedItem.ToString() select u).Count()

LINQ to Entities 需要将您的代码转换为 SQL。为此,需要将 ddlRoomType.SelectedItem.ToString() 转换为 constant,以便将其包含在 SQL 中。 Entity Framework 无法将其转换为常量,特别是因为它不知道 toString 方法中发生了什么样的处理。你到底懂不懂呢? toString()方法需要C#求值,不求值不能成为常量所以可以包含在SQL.

试试这个:

DLDbContext context = new DLDbContext();
//Counts how many versions of that room exists
var roomType = ddlRoomType.SelectedItem.ToString();
int RoomTypes = (from u in context.Room where u.type == roomType select u).Count();