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

老子叫甜甜 提交于 2020-01-03 08:14:09

问题


I have a varbinary(max) field in one of my tables but I don't need it every time and I'm looking for a way to fetch it from the database only when necessary. I'm using ADO.NET Entity Framework. How to do that?


回答1:


The solution was to create a separate table with the varbinary field and make 1-to-1 relationship between the tables




回答2:


It is not necessarily to create separate table. You should do several steps. Let's assume that we have table 'Documents' (Id, Name, Data (varbinary)).

  1. Open EF designer, copy and paste the 'Document' entity.
  2. Rename it to 'DocumentData'. Add mapping to 'Documents' table.
  3. Delete 'Data' property in 'Document' entity.
  4. Delete 'Name' property in 'DocumentData' entity.
  5. Right-click 'DocumentData' entity and add new Association. Select 1-to-1 association with 'Document' entity.
  6. Select new association, go to Properties, click '...' on 'Referential Constraint' field, select 'Document' entity as principal, leave all as default (Id -> Id) and click OK.

Now build the project.

NOTE. Now when creating new 'Document' entity you should also create new 'DocumentData' entity even if you don't want to place any data yet:

Document doc = new Document();

doc.Name = "My document";
doc.DocumentData = new DocumentData();

context.Documents.Add(doc);
context.SaveChanges();



回答3:


One way would be to project your result set into an anonymous type when you don't need the blob:

from entity in context.Entities
select new 
{
    Field1 = entity.Field1,
    Field2 = entity.Field2
}

In this example, only Field1 and Field2 will be loaded.

This method has the disadvantage that you cannot update the returned instance and do context.SaveChanges. Though I would argue that saving an instance without full knowledge of the instance is borderline unsafe. This method is good when you want a long list of return the instances, but will be querying for a single instance, varbinary field and all, before you actually update.




回答4:


You should remove your varbinary field from the table, and put it in another table, making one to one relationship between those. This is a good practice because you can easily implement lazy loading and other stuff..




回答5:


Table splitting. Entity Developer tool allows to perform this visually. You can map your entity for different tables.



来源:https://stackoverflow.com/questions/662873/how-to-load-varbinarymax-fields-only-when-necessary-with-ado-net-entity-framew

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!