簡體   English   中英

如何使用實體框架管理在 SQL Server 中存儲空字節數組?

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

我想通過以下過程將圖像保存在VARBINARY(max)類型的數據庫中:

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)

這是我如何設法使用 SQL 過程提取字段

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

這是我在 EF 中使用上述程序的方式

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

這是我設法在 PictureBox 中顯示二進制圖像的方法

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

此外,我的資產類型為維護圖像是byte[]

那么我該如何管理呢? 如果那是空的,我不會遇到麻煩嗎?

考慮一下,當輸入不為空時它可以正常工作

我建議在嘗試使用數據之前明確檢查 null/empty。

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

我會選擇將所有這些都包裝在 Try/Catch 塊中,以處理字節數據不包含圖像的情況。 (它發生了,尤其是隨着系統的成熟,有人支持將 PDF 之類的文件放入其中。)

還有一點建議:對於像圖像這樣的大型二進制數據,我建議更新架構以將它們移到與用戶以 1-0..1 關系鏈接的單獨表中。 (所以一個名為 UserImage 的新表,帶有 UserId 的 PK,然后可以在 UserImage 上使用 HasOptional 配置 User)原因是這些數據可能不會被頻繁訪問,您可能會在“上加入/選擇”用戶”相當頻繁。 如果您使用 User 作為參考,並使用這些較大的 blob 代碼預先/延遲加載 User,則會對性能產生影響。 如果用戶圖像數據位於單獨的相關表中,則您可以引用 User,而無需考慮該昂貴數據的性能成本,直到明確需要它為止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM