本文介绍了使用实体框架创建查询5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试转换为EF 5,但有 CreateQuery
有问题。任何帮助将不胜感激。谢谢你提前。
Trying to convert to EF 5 but having problems with CreateQuery
. Any help would be much appreciated. Thank you in advance.
这是代码:
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.......
推荐答案
我在此回应中假设您的MyEntities在EF5中继承自DbContext。
I assume in this response that your MyEntities inherits from DbContext in EF5.
使用SqlQuery的T)方法在DbContext.Database属性中完成同样的事情:
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)
{
}
}
}
如果您的实体框架模型来自ObjectContext(而不是DbContext),那么请参阅这个链接如何访问EF5中的CreateQuery方法。
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.
这篇关于使用实体框架创建查询5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!