Mostafa Moheb Mostafa Moheb - 3 months ago 31
C# Question

Disadvantages of using Entity Framework in cshtml view

Sometimes I put some of my C# code in my view (

) not all of my code. For example I have a table named LawCategory and I do this:

var db = new Contracts.Models.DataContext();
var LawCat = db.LawCategory.ToList();

and then use it like this:

<div class="col-md-6">
<select name="Type" id="Type" class="form-control">
<option value="0">All</option>
@foreach (var i in LawCat)
<option value="@i.ID" @(Request.QueryString["id"] == i.ID.ToString() ? "selected" : "")>@i.Name</option>

I want to know what is disadvantages of using datacontext in view and connect to database instead of send view model from controller?

Is it true that doing this, may cause set multi connection to database? (Entity Framework)


You can use DBContext (EntityFramework) code directly in View as it is allowed and execute perfectly.

Now problem comes with design and MVC pattern itself.

  1. In MVC pattern , we mostly use for separation of concern. Here view has more than one concern apart from managing view. It directly call EntityFramework and so it break that point.

  2. It make code less testable. As here we also want to look at each view as view might contains some code and that not specified in Controller so by looking at controller only we can not identify dependency.