【问题标题】:Execute Generic SQL query using Entity Framework C#使用实体框架 C# 执行通用 SQL 查询
【发布时间】:2013-06-26 10:54:05
【问题描述】:

我想执行 sql 查询。然后将检索到的值转储到网页中。我可以在 c# 中使用 SQLCommand。但是我如何使用实体框架来做到这一点。我觉得很难的原因是因为我不知道这个查询将在哪个表上运行(至于这个我将不得不解析选择查询)。请帮帮我。

【问题讨论】:

标签: c# sql entity-framework


【解决方案1】:
context.ExecuteStoreQuery<Product>("select * from table where id = {0}", 1);

ExecuteStoreQuery

【讨论】:

    【解决方案2】:

    我意识到已经有一个很好的答案,但我可以给你一个提示 - 你可以实现 Execute Around Method 模式来执行事务中的选择、插入和更新的通用查询。我是这样做的:

    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 查询实现数据适配器,您可以将其作为委托参数传递:

    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;
            });    
    }
    

    源:http://www.marcusnordquist.com/?p=66

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多