简体   繁体   中英

Why my SQL query does not work by Entity Framework?

I use his code for executing SQL query in entity framework :

using (var db = new VSServicesEntities())
            {                 
                const string selectCmd = @"if exists (Select top 1 IsUserOn From ServiceMembers Where ServiceCode={0} and Number={1}) 
                             Select isnull(IsUserOn,0) IsUserOn
                             From ServiceMembers Where ServiceCode={0} and Number={1}
                          else 
                             Select Null IsUserOn";
                 var data = db.ServiceMembers.SqlQuery(selectCmd, "A", 091242535970).ToList();
                if (data.Any())
                {

                   var serviceMember = data.First().IsUserOn;
                if (serviceMember.ToString() == "")
                    label1.Text = "";
                else
                    label1.Text = (serviceMember.ToString() == "True" ? "On" : "Off");
                }
    }

but it gives me an exception :

Must declare the scalar variable "@ServiceCode".

but i give value to ServiceCode= A , what is the problem?

EDIT 2: I edited my query on top, but now it gives me another exception :

The data reader is incompatible with the specified 'VSServicesModel.ServiceMember'. A member of the type, 'ServiceCode', does not have a corresponding column in the data reader with the same name

but my column name is exactly : ServiceCode !! what is the problem??

You aren't passing parameters correctly:

var data = db.ServiceMembers.SqlQuery(selectCmd, 
    new SqlParameter("@ServiceCode", "A"), 
    new SqlParameter("@Number", 091242535970)).ToList();

Edit

The type that EF will attempt to assign to data is the type of the element of ServiceMembers (assuming ServiceMember ). The only field you return is IsON which does not match the property IsUserOn which you reference. Try instead:

Select isnull(IsUserOn,0) AS IsUserON
...
Select Null AS IsUserON

Note that other properties will not be populated unless you return them from the query with matching names.

Edit You've changed your sql query - the binding was working correctly with ServiceCode=@ServiceCode and Number=@Number . At a guess, the reason why the Reader is complaining is because you are returning just one column ( IsUserON ) and trying to bind it to your full ServiceMember class. Either return all the columns (especially the primary key, presumably ServiceCode ), or alternatively create a new class just with the property IsUserON and then use the generic type overload db.SqlQuery<MyNewPoco>(cmd, ...) to bind it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM