Tải bản đầy đủ (.pdf) (6 trang)

Lập trình .net 4.0 và visual studio 2010 part 30 ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (189.67 KB, 6 trang )

CHAPTER 8  ENTITY FRAMEWORK

201

Creating all Primary Key Constraints


Creating primary key on [CustomerID] in table 'Customers'
ALTER TABLE [dbo].[Customers] WITH NOCHECK
ADD CONSTRAINT [PK_Customers]
PRIMARY KEY CLUSTERED ([CustomerID] ASC)
ON [PRIMARY]
GO
Creating primary key on [AddressID] in table 'Addresses'
ALTER TABLE [dbo].[Addresses] WITH NOCHECK
ADD CONSTRAINT [PK_Addresses]
PRIMARY KEY CLUSTERED ([AddressID] ASC)
ON [PRIMARY]
GO


Creating all Foreign Key Constraints


Creating foreign key on [CustomerCustomerID] in table 'Addresses'
ALTER TABLE [dbo].[Addresses] WITH NOCHECK
ADD CONSTRAINT [FK_CustomerAddress]
FOREIGN KEY ([CustomerCustomerID])
REFERENCES [dbo].[Customers]
([CustomerID])
ON DELETE NO ACTION ON UPDATE NO ACTION


GO
22. Click Finish.
23. You will receive a warning (Figure 8-21)—click Yes.

Figure 8-21. Warning displayed on generated T-SQL
That’s it—you can now run this SQL on your database and use the EDM in the standard way.
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.
CHAPTER 8  ENTITY FRAMEWORK

202
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.
Code Only/POCO
One of the biggest complaints about Entity Framework v1 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 Entity Framework 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 IPOCO) were developed involving inheritance and
implementing a number of interfaces to try and 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 EFV1 AND WANT POCO?

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

POCO 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;


CHAPTER 8  ENTITY FRAMEWORK

203
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 a new entry is added to the Film table. Notice
how our configuration class allows us to define mappings and property attributes.
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 on the designer surface and select Add Code Generation Item.
CHAPTER 8  ENTITY FRAMEWORK

204
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 on 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.
Julie Lerman (Author of Programming Entity Framework
and MVP)

There is so much to write home about in Entity Framework 4, from myriad designer improvements to
API changes. If I had to pick a shortened list it would include the greatly improved stored procedure
support, added support for n-tier development, support for POCO classes, which leads to agile
CHAPTER 8  ENTITY FRAMEWORK


205
development and unit testing, the use of T4 to generate code from an EDM, foreign key support, model
first design and Code-Only, which provides the ability to use Entity Framework without a model. Code-
Only support elicits joy from domain-driven developers.
Dane Morgridge

I have been using ORM tools for several years and decided to take a look at the Entity Framework when it
was released with .NET 3.5SP1. Previously, I had been using LINQ to SQL and given their similarities,
moving to Entity Framework wasn’t difficult. The first version of Entity Framework was missing quite a
few features that were present in most ORM tools, mainly lazy loading. I tend to personally prefer to
preload as much data as I can, so not having lazy loading wasn’t a huge problem for me. One of the
biggest problems I ran into was the fact that you didn’t have direct easy access to foreign keys, which
required you to pull back additional data to get basic relationship data. Other than a few API differences,
this was the biggest pain point in moving from LINQ to SQL to Entity Framework. Despite these issues
and its critics, I have grown to love the Entity Framework and have been using it in production since its
initial release.
There are really two paths into working with the Entity Framework, those who have used ORM tools
before and those that haven’t. Those that have used ORM tools before will quickly notice the features
that are missing and may be a barrier to adoption. Those coming from normal ADO.NET development
will likely not miss the features that aren’t included, since you can’t do things like lazy loading with
ADO.NET datasets or inline SQL. Version 4 of the Entity Framework will be a game changer. I have been
working with Visual Studio 2010 since the first public beta and I am very happy to see where the Entity
Framework is going. The product team has been listening to users and a majority of the issues with the
first version of Entity Framework have been addressed with version 4.
I am personally very excited about the features that allow for persistence ignorance, like POCO
classes and self-tracking entities. When building services and web applications, I like to have a data
layer that is ignorant of the database. This is for multiple reasons like reducing the amount of data that
goes over the wire and being able to use the same classes on both sides of the service. With version 1,
I have to write my own additional layer to achieve this. The way POCO classes are implemented, I can
use persistent ignorant classes that can also directly be used with the Entity Framework data context.

The added ability of T4 code generation allows me to generate those classes as well, so I don’t have to
code them by hand.
I am also very impressed with the implementation of model first development in Visual Studio 2010.
Visual Studio 2010 now has a model designer that you can use to create a database from. This allows you
to use Visual Studio as a database modeling tool instead of relying on third party modeling tools, which
can be very expensive. While modeling in Visual Studio 2010 doesn’t cover every single option you can
use when creating a database, combined with a good schema compare tool, it will allow you to simply
create and maintain data models.
Out of all the ORM tools I have used in the past, I always find myself using the Entity Framework
above all others. While version 1 had its shortcomings, it was still a good tool for interacting with
databases. I have done several presentations on the Entity Framework and every session has been
packed, which tells me there is great interest in the Entity Framework by the development community. I
believe that Entity Framework 4, with its new features, will be a first-class ORM and will continue to see
greater use. If you haven’t taken a good long look at the Entity Framework, now is the time.
CHAPTER 8  ENTITY FRAMEWORK

206
Conclusion
I have to admit I had heard nothing but bad things about Entity Framework before I starting writing this
chapter so I wasn’t looking forward to it. However, after working with EF for some time I have to admit I
really quite like it.
I am cautious, however, with recommending its use, since Microsoft can be fickle with their data
access strategies. I would consider that a mature open-source solution such as NHibernate probably has
less chance of being dropped and has a large community around to support and offer advice. Thus it
could be said that NHibernate is potentially a safer option from a future proofing point of view.
In conclusion, while EF is not as feature-rich as some of its competitors, it is arguably easier to use,
integrates well with other Microsoft technologies, performs well (
nhibernate-vs-entity-framework-a-performance-test/) and I heartily recommend you investigate it
further.
References/Further reading

• Programming Entity Framework by Julia Lerman (O’Reilly, 2009); a fantastic book—
can’t recommend enough)




• />the-entity-framework-is-not-just-around-domain-driven-design.aspx
• />confidence/



×