Trying to convert to EF 5 but having problems with CreateQuery
. Any help would be much appreciated. Thank you in advance.
This is the code:
using System;
using System.ServiceModel;
using System.Data.Objects;
namespace TestingOneServiceRole
{
public class Service1 : IService1
{
public void AddUser(string fullName, string userName, string password)
{
using (var context = new MyEntities())
{
context.AddToUser(new User()
{
UserName = userName,
Password = password,
FullName = fullName,
});
context.SaveChanges();
}
}
public string UserLoginNow(string username, string password)
{
string query = @"SELECT value blah.FullName FROM MyEntities.blah AS User WHERE blah.UserName = @username AND blah.Password = @password";
ObjectParameter[] parameters = new ObjectParameter[2];
parameters[0] = new ObjectParameter("username", username);
parameters[1] = new ObjectParameter("password", password);
using (var context = MyEntities())
{
ObjectQuery<string> results = context.CreateQuery<string>(query, parameters);
foreach (string result in results)
{
etc.......
I assume in this response that your MyEntities inherits from DbContext in EF5.
Use the SqlQuery(of T) method in the DbContext.Database property to accomplish the same thing:
public string UserLoginNow(string username, string password)
{
string query = @"SELECT value blah.FullName FROM MyEntities.blah AS User WHERE blah.UserName = @username AND blah.Password = @password";
object[] parameters = new object[2];
parameters[0] = username;
parameters[1] = password;
using (var context = MyEntities())
{
IEnumerable<string> results = context.Database.SqlQuery<string>(query, parameters);
foreach (string result in results)
{
}
}
}
If your entity framework model dervies from ObjectContext (as opposed to DbContext) then see this link provided by @MarkSowul on how to get access to the CreateQuery method in EF 5.
There are two steps:
One, add the reference to the class:
using System.Data.Entity.Infrastructure;
Two, rewrite your code as
var result= ((IObjectContextAdapter)context).ObjectContext.CreateQuery<blah_name>(query);
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.