Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# ASPX文件中的SQL查询:有更好的地方吗?_C#_Asp.net_Sql - Fatal编程技术网

C# ASPX文件中的SQL查询:有更好的地方吗?

C# ASPX文件中的SQL查询:有更好的地方吗?,c#,asp.net,sql,C#,Asp.net,Sql,我有一个“最佳实践”问题。我正在制作一个简单的个人博客应用程序,需要存储一些数据。从关注点分离的角度来看,我觉得写入数据库的逻辑应该存储在ASPX文件之外的其他地方。在ASPX文件中包含数据库逻辑是常见的做法,还是有更好的方法 下面是我在ASPX文件中编写的示例: private void updateUserInformation() { string connection_string = @"Provider=Microsoft.Jet.OLEDB.4.0;Data

我有一个“最佳实践”问题。我正在制作一个简单的个人博客应用程序,需要存储一些数据。从关注点分离的角度来看,我觉得写入数据库的逻辑应该存储在ASPX文件之外的其他地方。在ASPX文件中包含数据库逻辑是常见的做法,还是有更好的方法

下面是我在ASPX文件中编写的示例:

private void updateUserInformation()
    {
        string connection_string = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PersonalBlog.mdb";
        using (OleDbConnection connection = new OleDbConnection(connection_string))
        {
            string sqlString = "UPDATE USERS SET [FIRST]=?,[LAST]=?,[EMAIL]=?,[MODIFIED_AT]=? WHERE [ID]=?";
            using (OleDbCommand command = new OleDbCommand(sqlString, connection))
            {
                command.CommandType = CommandType.Text;
                command.Parameters.AddWithValue("FIRST", this.txtFirst.Text.Trim());
                command.Parameters.AddWithValue("LAST", this.txtLast.Text.Trim());
                command.Parameters.AddWithValue("EMAIL", this.txtEmail.Text.Trim());
                command.Parameters.AddWithValue("MODIFIED_AT", DateTime.Now.ToString());
                command.Parameters.AddWithValue("ID", Int32.Parse(this.txtUserID.Text.Trim()));
                connection.Open();
                int rowsAffected = command.ExecuteNonQuery();

                if (rowsAffected > 0)
                {
                    Response.Write("<script>alert('Row has been updated!');</script>");
                    Response.Redirect("CreateAccount.aspx");
                }
            }
        }
    }
private void updateUserInformation()
{
字符串连接_string=@“Provider=Microsoft.Jet.OLEDB.4.0;数据源=| DataDirectory |\PersonalBlog.mdb”;
使用(OLEDB连接=新OLEDB连接(连接\字符串))
{
string sqlString=“更新用户集[第一次]=?,[最后一次]=?,[电子邮件]=?,[修改地址]=?其中[ID]=?”;
使用(OleDbCommand命令=新的OleDbCommand(sqlString,connection))
{
command.CommandType=CommandType.Text;
command.Parameters.AddWithValue(“FIRST”,this.txtFirst.Text.Trim());
command.Parameters.AddWithValue(“LAST”,this.txtLast.Text.Trim());
command.Parameters.AddWithValue(“EMAIL”,this.txtEmail.Text.Trim());
command.Parameters.AddWithValue(“MODIFIED_AT”,DateTime.Now.ToString());
command.Parameters.AddWithValue(“ID”,Int32.Parse(this.txtUserID.Text.Trim());
connection.Open();
int rowsAffected=command.ExecuteNonQuery();
如果(行受影响>0)
{
Write(“警报('行已更新!');”;
重定向(“CreateAccount.aspx”);
}
}
}
}

最佳实践规定,数据访问属于应用程序的单独层(或文件)。我将假设您的大多数操作都是CRUD(创建/读取/更新/删除),因此将为您提供一个简单的解决方案:

将连接字符串移动到配置文件 将连接字符串直接放在代码中是不好的,因为当您从开发转移到生产时,您无法更改它。相反,将它们放在一个单独的配置文件中,这样您就可以更改它,而无需重新编译代码

在Web.config中,添加以下部分:

<configuration>
   <connectionStrings>
      <add name="DBConnectionString"
           connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\PersonalBlog.mdb"/>
   </connectionStrings>
</configuration>
集中数据访问代码 下一步是创建一个存储库来存放您的数据访问逻辑。使用ORM框架为您编写连接/命令代码是很常见的,因为这样您就不用编写T-SQL了。因为这个应用程序看起来很简单,所以我不会完全分离关注点,只给出一个更整洁的示例

此示例使用实体框架:

public class DatabaseContext : DbContext
{
   // name="DBConnectionString" is the <connectionString -> name> from Web.config
   public DatabaseContext() : base("name=DBConnectionString") { }

   public DbSet<User> Users { get; set; }

   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
       // Define mappings
       modelBuilder.Entity<User>().ToTable("USERS");
       modelBuilder.Entity<User>().HasKey(x=>x.Id);
   }
}
公共类数据库上下文:DbContext
{
//name=“DBConnectionString”是Web.config中的名称>
public DatabaseContext():base(“name=DBConnectionString”){}
公共数据库集用户{get;set;}
模型创建时受保护的覆盖无效(ModelBuilder ModelBuilder)
{
//定义映射
modelBuilder.Entity().ToTable(“用户”);
modelBuilder.Entity().HasKey(x=>x.Id);
}
}
从那里,您可以按如下方式更新您的ASPX:

private void updateUserInformation()
{
    int rowsAffected = 0;

    using(var dbContext = new DatabaseContext())
    {
        int userId = int.Parse(this.txtUserID.Text);

        // Load record to be updated - changes are tracked internally
        User userToUpdate = dbContext.Users.Find(userId);

        userToUpdate.First = this.txtFirst.Text.Trim();
        userToUpdate.Last = this.txtLast.Text.Trim();
        userToUpdate.Email = this.txtEmail.Text.Trim();
        userToUpdate.ModifiedAt = DateTime.Now;

        // Commit changes to DB
        rowsAffected = dbContext.SaveChanges();
    }

    if (rowsAffected > 0)
    {
        Response.Write("<script>alert('Row has been updated!');</script>");
        Response.Redirect("CreateAccount.aspx");
    }
}
private void updateUserInformation()
{
int rowsAffected=0;
使用(var dbContext=newdatabasecontext())
{
int userId=int.Parse(this.txtUserID.Text);
//要更新的加载记录-内部跟踪更改
User userToUpdate=dbContext.Users.Find(userId);
userToUpdate.First=this.txtFirst.Text.Trim();
userToUpdate.Last=this.txtLast.Text.Trim();
userToUpdate.Email=this.txtEmail.Text.Trim();
userToUpdate.ModifiedAt=DateTime.Now;
//将更改提交到数据库
rowsAffected=dbContext.SaveChanges();
}
如果(行受影响>0)
{
Write(“警报('行已更新!');”;
重定向(“CreateAccount.aspx”);
}
}

我认为您应该创建一个数据访问层。在该层中,您将存储包含查询方法的cs文件。这样,如果您需要从项目的另一部分访问此查询,或者将DLL添加到另一个项目中,它仍然是可重用的。请参见以下问题:如果您知道“关注点分离”的含义,那么答案就不足为奇了。数据库逻辑(或任何非表示逻辑)不应位于表示层。感谢您的见解。我会调查的。
private void updateUserInformation()
{
    int rowsAffected = 0;

    using(var dbContext = new DatabaseContext())
    {
        int userId = int.Parse(this.txtUserID.Text);

        // Load record to be updated - changes are tracked internally
        User userToUpdate = dbContext.Users.Find(userId);

        userToUpdate.First = this.txtFirst.Text.Trim();
        userToUpdate.Last = this.txtLast.Text.Trim();
        userToUpdate.Email = this.txtEmail.Text.Trim();
        userToUpdate.ModifiedAt = DateTime.Now;

        // Commit changes to DB
        rowsAffected = dbContext.SaveChanges();
    }

    if (rowsAffected > 0)
    {
        Response.Write("<script>alert('Row has been updated!');</script>");
        Response.Redirect("CreateAccount.aspx");
    }
}