Accessing Database Entities from Controller c# controller entity-framework separation-of-concerns



in a decent layout. Is it OK to pass through the business logic layer for accessing the database in an MVC model?IQueryable s orDbContext to a controller, objects?

Why? What are each's benefits and drawbacks?

In C#, I'm creating an ASP.NET MVC application. It makes use of the ORM EntityFramework.

Let's downplay this situation a little bit.

In a database table I have some cuddly, fluffy kittens. Each kitten has a name, a name link, a kitten id, a kitten fluffiness index, and a kitten. These correspond to a POCO created by EF namedKitten . In addition to the MVC project, I might use this class in other projects.

I possessKittenController which ought to bring the freshest kittens at/Kittens . The decision to choose the kitten may have some rationality, but not too much. I won't name sides, but I've been arguing with a friend over how to put this into practice.

Option 1: the controller's database

public ActionResult Kittens() // some parameters might be here
   using(var db = new KittenEntities()){ // db can also be injected,
       var result = db.Kittens // this explicit query is here
                      .Where(kitten=>kitten.fluffiness > 10) 
                      .Select(kitten=>new {
       return Json(result,JsonRequestBehavior.AllowGet);

Second choice: separate model

public class Kitten{
   public string Name {get; set; }
   public string Url {get; set; }
   private Kitten(){
        _fluffiness = fluffinessIndex;

   public static IEnumerable<Kitten> GetLatestKittens(int fluffinessIndex=10){ 
        using(var db = new KittenEntities()){ //connection can also be injected
            return db.Kittens.Where(kitten=>kitten.fluffiness > 10)
                     .Select(entity=>new Kitten(,entity.imageUrl))
    } // it's static for simplicity here, in fact it's probably also an object method
      // Also, in practice it might be a service in a services directory creating the
      // Objects and fetching them from the DB, and just the kitten MVC _type_ here


//----Then the controller:
public ActionResult Kittens() // some parameters might be here
    return Json(Kittens.GetLatestKittens(10),JsonRequestBehavior.AllowGet);

Notes: GetLatestKittens is maybe utilized elsewhere in the code, but it is improbable. You can employ the constructor ofKitten instead of altering the class for Kittens and using a static construction method. In essence, it's meant to be a layer over the database entities, freeing the controller from having to know anything about the real database, the mapper, or the entity framework.

  • Which design has advantages and disadvantages?
  • Is there a definite victor? Why?

Note: Of course, there are very other solutions that are valued as well.

1. Clarification Practically speaking, this application is not simple. Tens of controllers and thousands of lines of code make up this application, and tens of additional C# projects also use the entities. This instance uses a shortened test case.

5/23/2017 12:18:25 PM

Accepted Answer

7/18/2013 4:47:45 PM

Popular Answer

The second strategy is better. Let's try a weak comparison:

You go into a pizzeria and approach the counter. The pimpled cashier welcomes you to McPizza Maestro Double Deluxe and says, "May I take your order? ", his vacant eyes threatening to draw you in. Yes, please serve me a large pizza with olives. The cashier answers, "Okay," with a croaky "o" sound in his voice. One Jimmy Carter, he shouts in the direction of the kitchen.

You then receive a sizable pizza with olives after some waiting. Have you noticed anything odd? The cashier did not instruct the customer to "take some dough, spin it around like it's Christmas time, pour some cheese and tomato sauce, sprinkle some olives, and put it in an oven for about 8 minutes!" Now that I think about it, that's not at all strange. Simply said, the cashier serves as a bridge between the worlds of the kitchen and the customer who wants the pizza. The cashier has no idea that the cook cuts his pizza using Jimmy Carter (a diminishing resource, people) or buys it from aliens.

You are in that circumstance. Your cashier is intelligent. He can make a mean pizza. That doesn't mean he should be making pizza, or telling someone how to make pizza. The cook's responsibility is to do it. There is a division of duties, as several responses (particularly those from Florian Margaine and Madara Uchiha) showed. Even though the model only performs a single function call or even a single line, it doesn't matter because the controller is has no concern.

Now, suppose the proprietors determine that pizzas are only a fad. and you change to a chic burger restaurant, which is more modern. Reviewing what transpired,

You go inside a posh burger place and approach the counter. I'm happy to take your order. Welcome to Le Burger Maestro Double Deluxe. I'll order a single huge hamburger with olives, of course. Okay, one Jimmy Carter," he says as he turns to face the kitchen.

You then receive a substantial hamburger with olives (ew).

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow