asp.net-mvc - EF Core:将元素添加到集合而不检索完整对象
问题描述
我有一些看起来像这样的代码:
控制器:
foreach (Guid id in someModel.Ids)
{
var someSlowToFetchEntity = await dbContext.SlowClass.FindAsync(id);
someOtherEntity.AddSlowEntity(someSlowToFetchEntity)
}
建模 someOtherEntity:
private ObservableCollection<SlowClass> _SlowEntity = new();
public ObservableCollection<SlowClass> SlowEntity
{
get
{
return __lazyLoader.Load(this, ref _SlowEntity);
}
set
{
_SlowEntity = value;
}
}
public SlowClass AddSlowEntity(SlowClass slowClass)
{
SlowEntity.Add(slowClass);
return slowClass;
}
慢班:
namespace SomeDataModel {
public class SlowClass : Entity {
public static SlowClass Create(IEntityCreationContext ecc) {
return new SlowClass(ecc);
}
private string _Name;
public string Name {
get {
return _Name;
}
set {
if (_Name != value) {
NotifyPropertyChanging();
_Name = value;
NotifyPropertyChanged();
}
}
}
// This is potentailly huge(up to 50MB allowed)
private byte[] _Content;
public byte[] Content
{
get {
return _Content;
}
set {
if (_Content != value) {
NotifyPropertyChanging();
_Content = value;
NotifyPropertyChanged();
}
}
}
public override void LoadDefaults(DbContext dbc) {
base.LoadDefaults(dbc);
}
}
class _SlowClassConfiguration : _EntityWithMetaDataConfiguration, IEntityTypeConfiguration<Attachment> {
public void Configure(EntityTypeBuilder<SlowClass> builder) {
base.Configure<SlowClass>(builder);
builder.Property(x => x.Name);
builder.Property(x => x.Content);
}
}
}
数据库集:
public DbSet<SomeOtherEntity> SomeOtherEntity { get; set; }
public DbSet<SlowClass> SlowClass { get; set; }
问题是查找和检索慢速实体大约需要 30 秒(因为它是一个大实体,几 MB 大)。EF Core到底只需要保存slowEntity的id,有什么办法,不先取slowEntity直接保存id吗?
解决方案
看看这是否有帮助:高效更新 - EF Core
在这里,它谈论的是更新大量记录,但同样的建议可能适用于您的情况:
不幸的是,EF 目前不提供用于执行批量更新的 API。在引入这些之前,您可以使用原始 SQL 来执行性能敏感的操作:
context.Database.ExecuteSqlRaw("UPDATE [Employees] SET [Salary] = [Salary] + 1000");
因此,当 EF Core 没有有效的解决方案时,您可以求助于 SQL。
推荐阅读
- docker - Docker Compose 使用缓存构建命令并且在复制到 docker 时不拾取更改的文件
- ios - Swift Popup 返回值到父视图控制器
- php - PDO 读取数据库,但不登录系统
- r - 如何通过修改后的停止调用获得正确的环境打印输出
- java - 如何打印具有特定长度的所有单词以及该长度的乘积
- ms-access - 当它是一个 Make Table 查询时,DSum 查询很慢
- angular - 参考动态键位字段(Angular)
- python-3.x - Python在for循环中使用列表中的值?
- javascript - 使用什么框架来构建 Web 组件:lit-element vs stencil vs SkateJS?
- html - 号召性用语按钮卡在页面中间