保存到数据库之前比较字节数组

时间:2012-05-14 18:18:02

标签: asp.net-mvc entity-framework file-io bytearray

比较保存到数据库的图像不同的最佳方法是什么,从而节省了I / O.

情境:

我正在使用Entity Framework在MVC3中编写ASP.NET应用程序。我有一个用于我的UserProfile Controller的编辑操作方法。现在我想检查我已经发布回方法的图像是不同的,如果是,那么我想调用ObjectContext。 SaveChanges()如果它是相同的图像,那么移动上。

以下是我的代码的缩减版本:

    [HttpPost, ActionName("Edit")]
    public ActionResult Edit(UserProfile userprofile, HttpPostedFileBase imageLoad2)
    {
        Medium profileImage = new Medium();

        if (ModelState.IsValid)
        {
            try
            {
                if (imageLoad2 != null)
                {
                    if ((db.Media.Count(i => i.Unique_Key == userprofile.Unique_Key)) > 0)
                    {
                        profileImage = db.Media.SingleOrDefault(i => i.Unique_Key == userprofile.Unique_Key);
                        profileImage.Amend_Date = DateTime.Now;
                        profileImage.Source = Images.ImageToBinary(imageLoad2.InputStream);
                        profileImage.File_Size = imageLoad2.ContentLength;
                        profileImage.File_Name = imageLoad2.FileName;
                        profileImage.Content_Type = imageLoad2.ContentType;
                        profileImage.Height = Images.FromStreamHeight(imageLoad2.InputStream);
                        profileImage.Width = Images.FromStreamWidth(imageLoad2.InputStream);

                        db.ObjectStateManager.ChangeObjectState(profileImage, EntityState.Modified);
                        db.SaveChanges();

                    }
                }
            }
        }

所以我将我的图像作为varbinary(max)保存到SQL Server Express DB中,在我的实体中引用它作为字节数组。

是否仅仅是从帖子循环字节数组并将其与拉回到ObjectContext中的字节数组进行比较?

1 个答案:

答案 0 :(得分:3)

我不是直接比较字节数组,而是比较图像的哈希值。也许可以将以下内容提取到比较方法中:

SHA256Managed sha = new SHA256Managed();
byte[] imgHash1 = sha.ComputeHash(imgBytes1);
byte[] imgHash2 = sha.ComputeHash(imgBytes2);

// compare the hashes
for (int i = 0; i < imgHash1.Length && i < imgHash2.Length; i++)
{
    //found a non-match, exit the loop
    if (!(imgHash1[i] == imgHash2[i]))
        return false;
}
return true;