尝试转换为EF 5但遇到CreateQuery
问题。任何帮助将非常感激。提前谢谢。
这是代码:
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.......
答案 0 :(得分:2)
我在此回复中假设您的MyEntities继承自EF5中的DbContext。
使用DbContext.Database属性中的SqlQuery(of T)方法完成同样的事情:
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)
{
}
}
}
如果您的实体框架模型来自ObjectContext(而不是DbContext),那么请参阅此link provided by @MarkSowul,了解如何访问EF 5中的CreateQuery方法。
答案 1 :(得分:2)
有两个步骤:
一,添加对类的引用:
using System.Data.Entity.Infrastructure;
二,将代码重写为
var result= ((IObjectContextAdapter)context).ObjectContext.CreateQuery<blah_name>(query);