Wednesday, December 28, 2011

Entity Framework Code First C# and VB

This week I was trying to understand more about Entity Framework Code First. Nothing better that follow an example. Julie Lerman's video on Pluralsight have a great example in C# of code first. So, I decided to do the same in VB. However, before start I am going to show you how the project is organized:


Using NuGet we need to add the new EntityFramework library (which at this moment its version is 4.2) for these three projects.
In the Datalayer that is a class library we have a class named Context which has the following code:

   public class Context: DbContext     
    {
        public DbSet<Header> Headers { get; set; }
        public DbSet<Detail> Details { get; set; }
    }

In the DomainClass project we have the classes:
   
 public class Header
    {
        public int Id { get; set; }
        public string Field { get; set; }
    }

And Detail as:

 public class Detail
    {
        public int Id { get; set; }
        public string FieldInDetail { get; set; }
    }

In the console app we have the following code in the main:
         
           var header = new Header  { Field  = "Whatever you want to say" };
            var db = new Context();
            db.Headers.Add(header);
            db.SaveChanges();

So, I decided to run it and see how far we can get:

Excelent. When the project run for the first time is going to create a database in the SQLExpress instance. Something like this:


Easy. Of course we are not dealing with changes in the database when the model changes it. But, what happened when we translate this to VB.net:


Ok, I need to find the answer of that. I will do that today or tomorrow and I will update this post. Of course somebody might have an answer before I do this.

Update: I just find the problem. My translation from C# to VB was not quite right:

I had:

Public Class Header
    Public Id As Integer
    Public Field As String
End Class
Public Class Detail
    Public Id As Integer
    Public FieldInDetail As String
End Class

Instead of:
Public Class Header
    Public Property Id() As Integer
    Public Property Field() As String
End Class
Public Class Detail
    Public Property Id() As Integer
    Public Property FieldInDetail() As String
End Class

I was confused because as old VB developer I had the very bad habit (or good) that if I did not want a property with setter and getter I use a public field and that was perfectly fine. Now if you want to declare a property in one line you should use the Property clause.

Perfect. Problem solved. It is 10:30 p.m. I am ready for watching T.V.

Richard

No comments:

Post a Comment