8.14. Foreign Keys

In previous versions of EF, foreign key fields on entities were hidden from the developer in the generated model. Developers were expected to access the related entity directly instead of querying foreign key fields. This could mean making some additional database queries to join entities and writing some tedious code.

For example, in our code we might be creating a UI for managing FilmShowings. It would be a lot easier if when creating a new film showing we could just set the related FilmID property:

NewFilmShowing.FilmID = FilmID;

In EF4, you can. It may be worth questioning whether you should be working this way, but I think on the whole it avoids additional database queries.

8.14.1. Code-Only/POCOs

One of the biggest complaints about EF version 1 was that, unless you wanted to write some complex code, you had to work with the generated classes and associated data context. This dependence on EF made it harder to perform unit testing, create n-tier applications, and work with third-party systems.

A number of methods (loosely referred to as IPOCOs) were developed involving inheritance and implementing a number of interfaces to try to achieve this, but for many these were unsatisfactory solutions. EF4 will, however, allow you to create classes that have no dependency on EF whatsoever.

STILL USING EF1 AND WANT POCO?

Jaroslaw Kowalski describes a possible method for implementing POCO classes in EFv1:

http://code.msdn.microsoft.com/EFPocoAdapter


8.14.2. POCOs in EF4

Creating POCO classes in EF4 is very easy:

  1. Create a new console project called Chapter8.CodeOnly.

  2. Add a new class called Film.cs and enter the following code:

    public class Film
        {
            public int FilmID { get; set; }
            public string Title { get; set; }
            public string Description { get; set; }
            public int Length { get; set; }
        }

  3. Add a reference to the System.Data.Entity and Microsoft.Data.Entity.CTP assemblies.

  4. Add a new class called FilmModel.

  5. Now add the following using directives to the FilmModel class:

    using System.Data.Objects;
    using System.Data.EntityClient;

  6. Add the following code to FilmModel.cs:

    public class FilmModel : ObjectContext
    {
        public FilmModel(EntityConnection connection)
          : base(connection)
        {
            DefaultContainerName = "FilmModel";
        }
    
        public IObjectSet<Film> Film { get { return base.CreateObjectSet<Film>(); } }
    }

  7. In Program.cs, add the following using statements:

    using Microsoft.Data.Objects;
    using System.Data.SqlClient;

  8. Now add the following code to Program.cs (ensuring you amend the connection string to reflect the location of your example database):

    static void Main(string[] args)
    {
        var ctxBuilder = new ContextBuilder<FilmModel>();
        ctxBuilder.Configurations.Add(new FilmConfiguration());
    
        var ctx =
          ctxBuilder.Create(new SqlConnection(
            "server=localhost;UID=USERNAME;PWD=PASSWORD; database=book;Pooling=true")
          );
        var NewFilm =
          new Film { Description = "Code only", Length = 200, Title = "Total Recall" };
    
        ctx.Film.AddObject(NewFilm);
        ctx.SaveChanges();
        ctx.Dispose();
    }
    
    class FilmConfiguration : EntityConfiguration<Film>
    {
        public FilmConfiguration()
        {
            Property(f => f.FilmID).IsIdentity();
            Property(f => f.Title).HasMaxLength(100).IsRequired();
        }
    }

  9. That's it; run the application and you will find that a new entry is added to the Film table. Notice how our configuration class allows us to define mappings and property attributes.

8.14.3. Code Generation Templates

VS2010 contains a number of T4 templates. At the time of writing, there are two templates available: ADO.NET EntityObject Generator and ADO.NET Self-Tracking Entity Generator. To use the templates, simply right-click the designer surface and select Add Code Generation Item.

  1. Select the template you want to use (Figure 8-22).

    Figure 8.22. ADO.NET templates
  2. The template will then be added to your project (default name Model.tt).

  3. You will receive a security warning; click OK to this.

  4. To run the template, simply right-click it and select the Run Custom Tool option.

  5. The template will then run and generate code contained beneath the Model class (the default generated code is Model.cs if you don't rename anything). You can then utilize the generated code within your solution.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.163.229