Reputation: 5866
I am trying to learn MVC 3/4 using visual studio 2012. I have created a view, a model and controller. VS created all the database stuff for me. It added a gridview for me where I can add a new row, edit or delete too. I would like to change the way it selects the rows from the database. I know that I have to change the DbContext for that.
here is my DbContext,
public class ApartmentContext : DbContext
{
public ApartmentContext() : base("name=ApartmentContext")
{
}
// this part has to be changed****
public DbSet<Apartment> Apartments { get; set; }
}
public DbSet Apartments{...} returns the list I guess, but I want to change the way it selects the rows. For example; I want to select the rows whose "flag" column is set to 1. how do I do that?
thanks
Upvotes: 1
Views: 1394
Reputation: 8444
An alternative is to have a wrapping interface around the context to hide these details, so that is applies to every query transparently:
// Wrapping interface
public interface IApartmentRepository
{
IQueryable<Apartment> Apartments { get; }
}
// As before
public class ApartmentContext : DbContext
{
...
}
// Implementing class, hiding the DbContext object
public class EFApartmentRepository : IApartmentRepository
{
private ApartmentContext context = new ApartmentContext();
public IQueryable<Apartment> Apartments
{
get { return this.context.Apartments.Where(a => a.Flag == 1); }
}
}
// Your controller uses DI to get the controller
public class HomeController : Controller
{
private IApartmentRepository apartmentContext;
public HomeController( IApartmentRepository rep )
{
this.apartmentContext = rep;
}
}
The controllers IApartmentRepository
parameter can be hooked up to the EFApartmentRepository
by overidding the DefaultControllerFactory
class. You use a DI framework like NInject or StructureMap to insert the correct implementation into the constructor at runtime.
Upvotes: 0
Reputation: 14216
You can also use entity framework dbconext to execute your TSQL Statement or stored procedure. Following is a link for that.
http://www.dotnetjalps.com/2012/04/execute-tsql-statement-with.html
Upvotes: 0
Reputation: 18977
You should filter your results in the related controller, not in the DbContext. It could be like this in that controller:
...
ApartmentContext db = new ApartmentContext();
var apartments = db.Apartments.Where(a => a.Flag == 1);
...
and then use apartment
object to render your view
Upvotes: 2
Reputation: 19830
You need to create query. Object Apartments
represents table in database, not a list.
Upvotes: 1