Aria Esr
Aria Esr

Reputation: 5

Entity Framework ASP.Net MVC return only the desired records directly from the Entity Model

So I'm writing an Accounting application in which each user can have multiple businesses and therefore multiple "versions" of the application. I have added a Business table in SQL Server and all other tables have a BusinessId. I'm currently getting the current businessId like this in controllers:

public int CurrentBusiness 
{ 
    get 
    { 
        return db.AspNetUsers
                 .Find(User.Identity.GetUserId())
                 .CurrentBusiness
                 .Value; 
    } 
    set { } 
}

Then I'm using Linq Where statements to return the relevant records:

db.Invoices.Where(x=>x.BusinessId == CurrentBusiness);

I just wanna know if it will be possible to write this code directly in my Entity Model so I can then just write:

db.Invoices;

And it returns the Invoices with the BusinessId for the current User.

Upvotes: 0

Views: 126

Answers (2)

Manprit Singh Sahota
Manprit Singh Sahota

Reputation: 1339

This is not possible as your current user is managed by ASP. I think you should add a claim when user logs in so that you do not have to query each time for CurrentBussiness of user.

Moving further you can create a method that returns Invoice based on Current Business of user.

public List<Invoice> GetUserInvoice(int businessId)
{
    return db.Invoices.Where(x=>x.BusinessId == businessId);
}

OR

public List<Invoice> GetUserInvoice()
{
    int businessId = currentUserBusinessId;// get this line from user Claim.
    return db.Invoices.Where(x=>x.BusinessId == businessId);
}

Good luck and happy coding. :)

Upvotes: 1

Farzam Babar
Farzam Babar

Reputation: 100

As per understanding CurrentBusiness contains collection of invoices.

if you are lazyloading configuration than all invoices will also be included in the CurrentBusiness variable, just call like

var invoices = CurrentBusiness.Invoices .

If not than you can explicitly include while access to the db using include extension method. like

var business = db.Business.Include(b => b.Invoices).Where(b => b.UserId == User.Identity.GetUserId()).FirstOrDefault();

Hope I address your question. you should play by debugging it.

Regards, FB

Upvotes: 0

Related Questions