Can I lazy load scalar properties with the ADO.Net Entity Framework?

后端 未结 2 1115
旧巷少年郎
旧巷少年郎 2021-01-15 14:16

I\'ve got a database table Image with one huge column: Data.

\"One

I\'d rath

相关标签:
2条回答
  • 2021-01-15 14:46

    Yes I believe you do have to. I don't think it's possible with EF.

    You could make an explicit query for the columns you need, and then later for the data-column. Like the suggestion in this post:

    How to load varbinary(max) fields only when necessary with ADO.NET Entity Framework?

    But it seems like Linq To SQL provides the possibility, so I'll try to look into if it's coming to EF too.

    0 讨论(0)
  • 2021-01-15 14:58

    Do you have access to the data schema? In Entity Framework you can't have two entities that reference the same table, **at least you couldn't in the past. With that said. You could create a Sql VIEW with the data column.

    CREATE VIEW [dbo].[ImageData]
    SELECT
        Id,
        Data
    FROM Image
    

    Now you can create an Entity Called Image Data that mirrors your schema above.

    If you need to update the view, that's possible as well, you would simply need to create a trigger on the view called INSTEAD OF TRIGGER.

    -- INSERT Trigger
    CREATE TRIGGER [dbo].[TR_ImageData_Update] ON [ImageData]
    INSTEAD OF INSERT
    AS
    BEGIN
        UPDATE [Image]
        SET Data = i.Data
        FROM Inserted AS i
    END;
    GO
    

    This would probably be ideal in most cases. However if you don't have access to the database schema you might not be able to do this. Instead, you would create a default query off your Image Entity.

    public static IQueryable GetImages(this DbContext db)
    {
        var query = db.Images.AsQueryable();
        return query.Select(r => new Image() { Id = r.id....});
    }
    
    public static IQueryable GetImageData(this DbContext db, int imageId)
    {
        var query = db.Images.AsQueryable();
        query = query.Where(x => x.Id == imageId);
        query = query.Select(x => new ImageData() { Id = r.Id, Data = r.Data });
        return query;
    }
    
    0 讨论(0)
提交回复
热议问题