首页 > 解决方案 > 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吗?

标签: asp.net-mvcentity-framework-core

解决方案


看看这是否有帮助:高效更新 - EF Core

在这里,它谈论的是更新大量记录,但同样的建议可能适用于您的情况:

不幸的是,EF 目前不提供用于执行批量更新的 API。在引入这些之前,您可以使用原始 SQL 来执行性能敏感的操作:

context.Database.ExecuteSqlRaw("UPDATE [Employees] SET [Salary] = [Salary] + 1000");

因此,当 EF Core 没有有效的解决方案时,您可以求助于 SQL。


推荐阅读