Entity Framework 5.0 and FileTable

一曲冷凌霜 提交于 2019-12-06 13:16:16

Maybe you can try this.

Table:

PhotoTable(
PhotoID uniqueidentifier ROWGUIDCOL  NOT NULL,
PhotoImage varbinary(max) FILESTREAM  NULL,

)

Insert:

create procedure spPhotoInsert
   @PhotoID uniqueidentifier
   ,@sPhotoPath nvarchar(max)
   ,@PhotoImage varbinary(max)
 as
begin

    select 
        cast('' as  varbinary(max)) PhotoImage
    into 
        #ret1

    truncate table #ret1

    declare @strSql nvarchar(max) = 'select * from OPENROWSET(BULK ''' 
                                    + @sPhotoPath + ''',SINGLE_BLOB) AS PhotoImage'
    insert into #ret1 EXEC(@strSql)

    insert into
        PhotoTable
           (
           PhotoID
           ,PhotoImage
           )
    select
        @PhotoID
        ,PhotoImage
    from
        #ret1

    drop table #ret1

end

Update:

create procedure spPhotoUpdate
   @PhotoID uniqueidentifier
   ,@sPhotoPath nvarchar(max)
   ,@PhotoImage  varbinary(max)
as
begin

    select 
        cast('' as  varbinary(max)) PhotoImage
    into 
        #ret1
    truncate table #ret1


    declare @strSql nvarchar(max) = 'select * from OPENROWSET(BULK ''' 
                                    + @sPhotoPath + ''',SINGLE_BLOB) AS PhotoImage'
    insert into #ret1 EXEC(@strSql)

    update
        PhotoTable
    set
        PhotoImage = r.PhotoImage
    from
        PhotoTable, #ret1 r
    where
        PhotoID = @PhotoID

    drop table #ret1

end

Delete:

create procedure PhotoDelete
   @PhotoID uniqueidentifier
as
begin

    delete
        PhotoTable
    where
        PhotoID = @PhotoID

end

And the view:

CREATE VIEW vPhotoTable
AS
    select
       PhotoID
       ,'' as sPhotoPath
       ,PhotoImage
    from 
        PhotoTable

After this, the images can be read / write with EF as follows:

//InsertPhoto(sPath) 
Entities db = new Entities();
vPhoto p = db.vPhotos.CreateObject();
p.PhotoID = Guid.NewGuid();
p.sPhotoPath = sPath;
db.vPhotos.AddObject(p);
db.SaveChanges();

//UpdatePhoto(PhotoID,sPath):
Entities db = new Entities();
vPhoto p = db.vPhotos.Where(x => x.PhotoID == PhotoID).Single();
p.sPhotoPath = sPath;
db.ObjectStateManager.ChangeObjectState(p, EntityState.Modified);
db.SaveChanges();

//DeletePhoto(PhotoID):
Entities db = new Entities();
vPhoto p = db.vPhotos.Where(x => x.PhotoID == PhotoID).Single();
db.vPhotos.DeleteObject(p);
db.SaveChanges();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!