2

尝试转换为 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.......
4

2 回答 2

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),请参阅@MarkSowul 提供的此链接,了解如何访问 EF 5 中的 CreateQuery 方法。

于 2013-04-26T16:55:30.617 回答
2

有两个步骤:

一、添加类的引用:

using System.Data.Entity.Infrastructure;

二,将您的代码重写为

var result= ((IObjectContextAdapter)context).ObjectContext.CreateQuery<blah_name>(query);
于 2015-03-25T18:23:30.753 回答