网上找了两个,一个内存表,一个临时表. 1 安装包: EntityFrameworkCore.MemoryJoin //内存表直接用select union拼接查询 http://tsherlock.tech/2018/03/20/joining-in-memory-list-to-entity-framework-query/ DbContext类中加
1 安装包: EntityFrameworkCore.MemoryJoin //内存表 直接用select union拼接查询 http://tsherlock.tech/2018/03/20/joining-in-memory-list-to-entity-framework-query/
DbContext类中加入: protected DbSet<QueryModelClass> QueryData { get; set; } // 注意升迁代码中 删除此表的升迁代码
2 引用: https://dev.azure.com/pawelgerr/_git/Thinktecture.EntityFrameworkCore ; 或者: https://github.com/yangzhinong/Thinktecture.EntityFrameworkCore 编译后的dll ConfigureServices方法中加入: services.AddDbContext<SalesDbContext>(options => { options.UseSqlServer(_appConfiguration.GetConnectionString("Default"), opts => { opts.AddTempTableSupport(); }); }); 3. 定义通用的Repository的接口和实现
3.1 public interface ITempTableRepository { IQueryable<T> FromLocalList<T>(IList<T> data) where T : class; Task<IQueryable<T>> BulkInsertIntoTempTableAsync<T>(IEnumerable<T> entities) where T : class; }
3.2 public class TempTableRepository : SalesRepositoryBase<CodeTemplate<Guid>, Guid>, ITempTableRepository { public TempTableRepository(IDbContextProvider<SalesDbContext> dbContextProvider) : base(dbContextProvider) { } public async Task<IQueryable<T>> BulkInsertIntoTempTableAsync<T>(IEnumerable<T> entities) where T : class { var query = await Context.BulkInsertIntoTempTableAsync(entities, new SqlTempTableBulkInsertOptions() { PrimaryKeyCreation = PrimaryKeyCreation.None, }); return query; } public IQueryable<T> FromLocalList<T>(IList<T> data) where T : class { return Context.FromLocalList(data); } }
3.3 DbContext中定义
public DbQuery<ImpTestTemp> ImpTestTemps { get; set; } ==========================
4使用类中 注入ITempTableRepository即可
private readonly IObjectMapper _objectMapper; private readonly IRepository<Area, Guid> _area; private readonly ITempTableRepository _tempTableRepository; public AreaService(IRepository<Area, Guid> area, IObjectMapper objectMapper, ITempTableRepository tempTableRepository) { _area = area; _objectMapper = objectMapper; _tempTableRepository = tempTableRepository; }
public async Task<IEnumerable<GetAreaByParentIdOutput>> GetAreaByParentIdAsync(Guid? parentId) { var lst = new List<ImpTestTemp> { new ImpTestTemp { Id = 1, AreaId=new Guid("179A9943-EC6C-4923-8B75-00818198008E") ,Code = "123", Name = "yzn", Sorce=98.5m }, new ImpTestTemp { Id = 2, AreaId= new Guid("48E8124C-789B-4158-BE9C-00507403DF7E"), Code = "456", Name = "seq" , Sorce=99.4m} }; var queryList = await _tempTableRepository.BulkInsertIntoTempTableAsync(lst); //数据多可以用此方法
var queryList2 = _tempTableRepository.FromLocalList(lst); // 数据少可用此方法 var efQuery = (from t in queryList join a in _area.GetAll() on t.AreaId equals a.Id select new { t.Code, AreaCode = a.Code, a.Name }).ToList(); retun null; } }