简体   繁体   中英

How to implicitly convert Byte[] to string when building model inside the controller

I am in the process of loading all the products belonging to unique categories on an index page with the request product/index/[Category ID] .

I have a ProductViewModel class which contains implicit methods to convert types between the two and also a Product entity model class. The implicit method to convert a Product entity to a ProductViewModel contains the method to convert a byte to a base64 string and I use this in my controller successfully to create new categories and products.

public class ProductViewModel
    {
        public int Id { get; set; }
        [Required, Display(Name="Product Name")]
        public string Name { get; set; }
        [Required, DataType(DataType.Upload)]
        public HttpPostedFileBase Image { get; set; }
        public string OutputImage { get; set; }
        [Required]
        public Decimal Price { get; set; }

        public static byte[] ConvertToByte(ProductViewModel model)
        {
            if (model.Image != null)
            {
                byte[] imageByte = null;
                BinaryReader rdr = new BinaryReader(model.Image.InputStream);
                imageByte = rdr.ReadBytes((int)model.Image.ContentLength);

                return imageByte;
            }

            return null;
        }

        // ViewModel => Model | Implicit type Operator
        public static implicit operator Product(ProductViewModel viewModel)
        {
            var model = new Product
            {
                Id = viewModel.Id,
                Name = viewModel.Name,
                Image = ConvertToByte(viewModel),
                Price = viewModel.Price
            };

            return model;
        }

        // Model => ViewModel | Implicit type Operator
        public static implicit operator ProductViewModel(Product model)
        {
            var viewModel = new ProductViewModel
            {
                Id = model.Id,
                Name = model.Name,
                OutputImage = string.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(model.Image)),
                Price = model.Price
            };

            return viewModel;
        }

    }

However when passing a model containing all products belonging to a unique category ID to be displayed on the products View , I am not able to implicitly convert a byte to a string. The method that I use as an alternative is not accepted with the error:

LINQ to Entities does not recognize the method 'System.String Format(System.String, System.Object)' method, and this method cannot be translated into a store expression.

The Model in the Controller is the following:

var products = (await db.Categories.Where(c => c.Id == id).Select(p => p.Products.Select(x => new 
    ProductViewModel { Id = x.Id, Name = x.Name, OutputImage = (string.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(x.Image))), Price = x.Price})).ToListAsync());
return View(products);

The Model type I give the View is the following:

@model List<IEnumerable<ValueVille.Models.ProductViewModel>>

you can't use string.Format() in a LINQ expression instead of that you can use it in Name setter :

public class ProductViewModel {

    public string Name{
      get
      {
         return this.Name;
      }
      set{
           this.Name = value;
           this.OutputImage  = string.Format("data:image/jpg;base64,{0}", Convert.ToBase64String(value))
      }
    }
}

and in the controller :

var products = (await db.Categories.Where(c => c.Id == id).Select(p => p.Products.Select(x => new 
                    ProductViewModel { Id = x.Id, Name = x.Name, Convert.ToBase64String(x.Image))), Price = x.Price})).ToListAsync());

I initially assumed you could still assign a byte[] to a string property, to have a byte[] value inside your setter and convert from byte to string inside the setter. If the property is a string, the value assigned to this property must be already a string.

A property assignment is NOT a conversion so it will never work as long as you try to assign directly x.Image which is a byte array to OutputImage which is a string.

You could keep the Image property as a byte array and to have an ImageHelper such as http://www.itorian.com/2012/10/html-helper-for-image-htmlimage.html

You would keep a byte array in your model :

Image = x.Image

And so you would pass this byte array to this helper.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM