我想执行sql query.And然后将检索到的值转储到网页中。我可以在c#中使用SQLCommand。但是我如何使用Entity Framework来实现这一点。我觉得困难的原因是因为我不知道这个查询将在哪个表上运行(至于这个我将不得不解析select查询)。请帮帮我。
答案 0 :(得分:5)
context.ExecuteStoreQuery<Product>("select * from table where id = {0}", 1);
答案 1 :(得分:0)
我意识到已经有了一个很好的答案,但我可以给你一个提示 - 你可以实现Execute Around Method模式来执行事务中的select,insert和update的泛型查询。我这样做了:
internal class CommonDataTool
{
internal delegate object SqlCommandDelegate();
/// <summary>
/// Use only for select where (a) return value(s) is/are expected and/or required
/// </summary>
/// <typeparam name="T"> Expected datacontext model return type, example: DataContext.User</typeparam>
/// <param name="context"> The DataContext (YourDataModel) instance to be used in the transaction </param>
/// <param name="action"> Linq to Entities action to perform</param>
/// <returns> Returns an object that can be implicitly casted to List of T where T is the expected return type. Example: List of DataContext.User</returns>
internal List <T> ExecuteSelect<T>(YourDataModel context, SqlCommandDelegate action)
{
using (context)
{
var retVal = action(); return ((ObjectQuery<T>)retVal).ToList();
}
}
/// <summary>
/// Use for updates and inserts where no return value is expected or required
/// </summary>
/// <param name="context"> The DataContext (YourDataModel) instance to be used in the transaction </param>
/// <param name="action"> Linq to Entities action to perform</param>
internal void ExecuteInsertOrUpdate(YourDataModel context, SqlCommandDelegate action)
{
using (context)
{
using (var transaction = context.BeginTransaction())
{
try
{ action(); context.SaveChanges(); transaction.Commit(); }
catch (Exception )
{ transaction.Rollback(); throw; }
}
}
}
}
public static class ObjectContextExtensionMethods
{
public static DbTransaction BeginTransaction( this ObjectContext context)
{
if (context.Connection.State != ConnectionState .Open) { context.Connection.Open(); }
return context.Connection.BeginTransaction();
}
}
这很好,因为您可以使用简单的linq查询实现dataadapter,您可以将其作为委托参数传递:
var users = _dataTool.ExecuteSelect<DataContext.User>(Db, GetUsers);
private static object GetUsers()
{
return (from u in Db.User select U).ToList();
}
另一个好处是您的更新/插入是在事务中运行的,而无需在linq查询中明确声明它们。
示例:
public void UpdateUser(DomainUser user)
{
_dataTool.ExecuteInsertOrUpdate(Db, () =>
{
Db.User.First(u => u.UserId == user.Id).Email = user.Email;
Db.User.First(u => u.UserId == user.Id).Name = user.Name;
Db.User.First(u => u.UserId == user.Id).LastName = user.LastName;
Db.User.First(u => u.UserId == user.Id).Password = user.Password;
return null;
});
}