简体   繁体   中英

How to manage to store null byte array in SQL Server with Entity Framework?

I would want to save images in the database with VARBINARY(max) type by this procedure:

ALTER proc [dbo].[User_Create]
(@BirthCertificateImage varbinary(max),
@BookletImage varbinary(max),
@GreenCardImage varbinary(max))
as
insert into [User]
(BirthCertificateImage,BookletImage,GreenCardImage)
values
(@BirthCertificateImage,@BookletImage,@GreenCardImage)

And here is how I managed to extract fields with SQL procedure

ALTER proc [dbo].[User_GetById]
(@UserId int)
as
select * from [User]
where
Id = @UserId

And here is how I'm using the mentioned procedure in the EF

var user = await db.Database.SqlQuery<UserModel>("User_GetById @UserId"
, new SqlParameter("UserId",id)).SingleOrDefaultAsync();

And here is how I managed to show the binary image in a PictureBox

var birthCertificateMs = new 
MemoryStream(response.Entity.BirthCertificateImage);
birthCertificatePictureBox.Image = Image.FromStream(birthCertificateMs);
birthCertificateMs.Close();

Also, my property's type for Maintenance the image is byte[]

So how can I manage it? If that was null do I won't get in trouble?

Consider, it works correctly when input is not null

I would recommend explicitly checking for null/empty before attempting to use the data.

if(response.Entity.BirthCertificateImage != null && response.Entity.BirthCertificateImage.Length > 0)
{
    using(var birthCertificateMs = new MemoryStream(response.Entity.BirthCertificateImage))
    {
        birthCertificatePictureBox.Image = Image.FromStream(birthCertificateMs);
    }
}

and I would opt to wrap all of that in a Try/Catch block to handle where the byte data doesn't contain an image. (It happens, especially as systems mature, someone supports chucking a PDF or such in there.)

One other bit of advice: for large binary data such as images, I would recommend updating the schema to move these off into a separate table linked in a 1-0..1 relationship with User. (So a new table called UserImage with a PK of UserId, then User can be configured with a HasOptional on UserImage) The reason for this is that this data is likely not going to be accessed that frequently, where you might Join/Select on "User" fairly often. If you use User as a reference and code eager/lazy-loads a User with those larger blobs, it will have a performance impact. If the user image data is in a separate related table, you can reference User without a performance cost of that expensive data until it is explicitly needed.

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