MVC 4 Views and Razor code (and showing an aggregation from an entity)

This is an example situation where Razor can be useful to allow code on a view: in this case, I have a view model like this one (very simplified):

public class Product
{
public Guid ProductId {get;set;}
public string Description {get;set;}

public virtual List ProductTransactions {get;set;}

}

public class ProductTransaction
{
public Guid TransactionId {get;set;}
public decimal Amount {get;set;}

public Guid ProductId {get;set;}
[ForeignKey("ProductId")]
public virtual Product Product {get;set;}

}

then, if I want to see a list of products with total amounts, in my view, I could use something like this:

<table>
  <thead>
    <tr>
      <td>
          @Html.LabelFor(x => x.Product[0].Description)
      </td>
      <td>
           @Html.LabelFor(x => x.Product[0].ProductTransactions[0].Amount)
      </td>
     </tr>
   </thead>
   <tbody>
    @foreach (var product in Model.Product) 
      {
       <tr>
         <td>
             @Html.DisplayFor(x => product.Description)
         </td>
        <td>
           @{ decimal totalAmount=0;
           foreach (var transaction in Product.ProductTransactions)
              {
                totalAmount= totalAmount+ transaction.Amount;
               }
            @Html.DisplayFor(x => totalAmount)
            }
       </td>
      </tr>
      }
    </tbody>
</table>

Of course this is not the complete code of the View, I just focused on what’s relevant to the use of code inside the view using Razor, for a specific purpose, in this case, obtain aggregation of the Amount for each one of the products in the corresponding entity (at the DB).

Cheers.

EF code first managing multiple foreign keys to a single entity

It is great to use code first, from our classes that represent entities, to be able to create the entities at the database and, through the navigation properties, allow us to get related data in our view models. It is great because we save time and make us to write a simpler code.

We can find ourselves in a case (not a rare one) in which we have a class with more than one foreign keys relating, both of them, to the same class (read entity). In this case we can use as follows, lets say, in our example we have the classes:

public class Employee

{
public int EmployeeId {get;set:}
public string Name {get,set;}
public virtual List<FactoryProcess> Shift1 {get; set}
public virtual List<FactoryProcess> Shift2 {get; set;}
}

public class FactoryProcess
{
public int ProcessId {get;set;}
public int Operator1Id { get; set; }
public virtual Employee Operator1 { get; set; }
public int Operator2Id { get; set; }
public virtual Employee Operator2 { get; set; }

}

And at the context class (this will do the “magic” completing in appropriated way the necessary relations between entities):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove();
            modelBuilder.Entity()
                .HasRequired(m => m.Operator1)
                .WithMany(t => t.Shift1)
                .HasForeignKey(m => m.Operator1Id)
                .WillCascadeOnDelete(false);
            modelBuilder.Entity()
                .HasRequired(m => m.Operator2)
                .WithMany(t => t.Shift2)
                .HasForeignKey(m => m.Operator2Id);       

        }

Changing Development Perspectives – Entity Framework and Code First

It is until the last 2 projects I’ve been working that I started to use code first. This is the first article of a series I plan to write on my experiences on this topic.

I have to recognize my friend and supervisor at my new job at Zgura for promoting its use in our development projects. Now I have had the opportunity to work with it, I’ll argue for its use, even if I already have an existent database, no doubts when starting with a new one.

It is great to use it with MVC 4. You just have to create your Models folder (we usually keep that in another project, at the VS solution), add classes, decorate properties as necessary, enable migrations and update database.

The concept works great as, after the initial learning curve, it helps to increase greatly speed of development, more if it is combined with view models.

Tip: if you keep the models in a separated project, remember to let the system know what is the name of the project containing the models to be used by code first migrations:

Enable-Migrations -ProjectName “MyProjectModelName” -StartUpProjectName “MyStartupProjectName”

These instructions for migrations are executed from the menu Tools/Library Package Manager/Package Manager Console in Visual Studio 2012.

Cheers.