0
votes

Well, here goes another noob question: So I made this app where different customer have access to their accounts. Everything is ok, they login, by roles I can get who gets what though entity framework. The thing is, with time, the database will grow A LOT. For example: Customers have access to their "bills to pay". For now, there are only a couple thousand of them and a simple "Where" lambda expression can do the trick. But as said, the base will grow. The scenario: Every record, has a "company" field, which determines the company which the record belongs to. Users have roles, where I store what companies that specific user can access data. So one user can access multiple companies data if it is configured this way. My question is: Is there a way to initialize entity framework scope passing on the user's roles so the scope contains data which "belong" to that user? Something like:

using (MyThingy scope = new MyThingy(user.Roles))
{
    //scope.Bills here will contain only bills which "payer" or "holder" 
    //are companies within user.Roles
    List<Bill> billsToPay = scope.Bills.Where(c => 
    c.DueDate == DateTime.Now);

}

So, is it possible? If so, what would be the best approach?

1
You have to do 30 pushups for referring to your DbContext as "MyThingy". - Sam
Can I switch for 50 squats? - user2960560

1 Answers

0
votes

There are many ways to do this. You may want to read up on joins. Here are a couple of approaches that may work:

// brings back a lot of Bills from the db into memory......
using (DbContext scope = new DbContext())
{
    //scope.Bills here will contain only bills which "payer" or "holder" 
    //are companies within user.Roles
    IEnumerable<Bill> billsToPay = scope.Bills.Where(c => c.DueDate == DateTime.Now );


    // this part happens in memory
    List<Bill> bills = billsToPay
    .Where(c => user.Roles.Any(role => c.payer == role.payer || c.holder == role.holder))
    .ToList();

}

// more efficient.. I did this from memory.  Syntax may not be perfect....

using (DbContext scope = new DbContext())
{
    //scope.Bills here will contain only bills which "payer" or "holder" 
    //are companies within user.Roles

    var query = from u in scope.Users
    from role in u.Roles
    from b in scope.bills.Where(b => b.DueDate == DateTime.Now && (b.roleID == role.roleID || b.holderID == role.holderID))
    where u.userID == user.userID
    select b;
}