gpt4 book ai didi

linq - 从 Entity Framework Core 的导航属性中选择对象列表

转载 作者:行者123 更新时间:2023-12-04 07:14:43 24 4
gpt4 key购买 nike

我有以下实体,它有一个 导航属性。

public class Member
{
public Member()
{
Id = 0;
IsActive = true;
BillDetails = new List<BillDetail>();
}

public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public bool IsActive { get; set; }
public int? OrgId { get; set; }
public IList<BillDetail> BillDetails { get; set; }
}

我有一个通用存储库,它是:
public abstract class BaseRepository<TEntity, TId> : IRepository<TEntity, TId> where TEntity : class
{
private readonly IApplicationDbContext _db;

public BaseRepository(IApplicationDbContext db)
{
_db = db;
}

public virtual void Add(TEntity entity)
{
_db.Set<TEntity>().Add(entity);
_db.Entry(entity).State = EntityState.Added;
}

public virtual bool Update(TEntity entity)
{
_db.Set<TEntity>().Attach(entity);
_db.Entry(entity).State = EntityState.Modified;
return true;
}

public virtual bool Delete(TEntity entity)
{
_db.Set<TEntity>().Remove(entity);
_db.Entry(entity).State = EntityState.Deleted;
return true;
}

public virtual IQueryable<TEntity> Query()
{
return _db.Set<TEntity>().AsQueryable();
}

public virtual EntityEntry<TEntity> Entry(TEntity entity)
{
return _db.Entry(entity);
}

public void Attach(TEntity entity)
{
if (entity == null || _db.Entry(entity).State != EntityState.Detached)
return;

_db.Set<TEntity>().Attach(entity);
}

public void Detach(TEntity entity)
{
if (entity == null)
return;

_db.Entry(entity).State = EntityState.Detached;
}

public abstract Task<TEntity> FindAsync(TId id);
}
从我的服务类中,我想获取以下类型的对象集合
public class MemberBill
{
public int MemberId {get; set;}
public decimal BillAmount {get; set;}
}
在我的服务类中,我有以下查询。现在如何从以下查询中获取对象列表( MemberBill )?
var query = (_memberRepository.Query().Where(x => x.IsActive == true && x.OrgId == orgId)
.Include(x => x.BillDetails.Where(y => y.IsActive == true))).AsNoTracking().AsQueryable();

List<IList<BillDetail>> memberBills = query.Select(x => x.BillDetails).ToList();

memberBills.Select(x => new MemberBill
{
MemberId = x.
}).ToList();
请帮我找到解决方案。

最佳答案

尝试这个

var query = _memberRepository.Query()
.Where(x => x.IsActive == true && x.OrgId == orgId)
.Include(x => x.BillDetails.Where(y => y.IsActive == true))
.AsNoTracking()
.ToList();

var memberBills=new List<MemberBill>();

foreach(var m in query)
{
memberBills.Add( new MemberBill
{
MemberId= m.Id,
BillAmount=m.BillDetails.Sum(i=> i.Amount)
});
}

关于linq - 从 Entity Framework Core 的导航属性中选择对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68837721/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com