Lập trình .net 4.0 và visual studio 2010 part 27 docx

6 255 0
Lập trình .net 4.0 và visual studio 2010 part 27 docx

Đang tải... (xem toàn văn)

Thông tin tài liệu

CHAPTER 8  ENTITY FRAMEWORK 185 What Happens If My Database Structure Changes? When you make changes to your database then you will also need to update your EDM. To update the model simply right-click on the design surface and select Update Model from Database. Visual Studio will then bring up a dialog box allowing you to add additional tables and fields (Figure 8-8). Note that this release of EF improves the resolution of conflicts/orphaned model elements in the model browser window: Figure 8-8. Update Model from Database Querying Data EF allows you to query objects in a number of different ways: • LINQ to Entities (L2E) • ObjectQuery methods • Entity SQL Whichever query method you use, the query gets transformed into the same query tree structure that is then processed by your model's data source provider. LINQ to Entities LINQ to Entities (L2E) is probably the easiest query method. L2E gives you rich query functionality and Intellisense support, and it is very easy to use. Lets write some code to iterate through our Orders and OrderItem tables displaying information about these entries. CHAPTER 8  ENTITY FRAMEWORK 186 1. Open Program.cs. 2. Modify the Main() method to the following (note your entity set will, by default, be prefixed with the same name as the database—in the following example, mine is Book). static void Main(string[] args) { BookEntities ctx = new BookEntities(); var query = from o in ctx.Orders select o; foreach (Order order in query) { Console.WriteLine("Order: " + order.OrderID.ToString() + " " + order.Firstname + " " + order.Lastname); order.OrderItems.Load(); foreach(OrderItem orderItem in order.OrderItems) { Console.WriteLine("Adult: " + orderItem.QtyAdult.ToString() + " Child:" + orderItem.QtyChild.ToString()); } Console.WriteLine(""); } Console.ReadKey(); } The results are shown in Figure 8-9. Figure 8-9. Output of LINQ to Entities query CHAPTER 8  ENTITY FRAMEWORK 187 ObjectQuery You can also query EF objects with the ObjectQuery class. Let’s take a look at this now. 1. Add the following using directive to Program.cs: using System.Data.Objects; 2. Replace the LINQ query with the following line of code (Note that it refers to the current entity, which in this case is Order): ObjectQuery<Order> query = ctx.Orders.OrderBy("it.OrderID"); Entity SQL Entity SQL is similar to T-SQL (but has its own EF-specific features and intricacies); the following is an example Entity SQL query: string queryString = @"SELECT VALUE o FROM BookEntities.Orders AS o"; ObjectQuery<Order> query = new ObjectQuery<Order>(queryString, ctx, MergeOption.NoTracking); We have barely touched what Entity SQL is capable of, so for more information (on anything EF related) please refer to Julia Lerman’s book Programming Entity Framework , published by O’Reilly. CRUD Operations in EF When you utilize EF, a connection to a database called an object context is created. When new entities are created or properties changed they are not written back to the database immediately; rather a flag is set on the entity to indicate that it has changed, but not saved to the database (a dirty state). Changes are then saved back to the database when the SaveChanges() method is called on the object context. Creating The following example shows how to create a new Film entity with a related FilmShowing entity and save the new items back to the database: BookEntities ctx = new BookEntities(); Film NewFilm = new Film(); NewFilm.Title = "New film"; NewFilm.Description = "New film"; NewFilm.Length = 300; FilmShowing NewFilmShowing = new FilmShowing(); NewFilmShowing.Screen = 5; NewFilmShowing.ShowingDate = System.DateTime.Now; NewFilm.FilmShowings.Add(NewFilmShowing); ctx.AddObject("Films", NewFilm); ctx.SaveChanges(); CHAPTER 8  ENTITY FRAMEWORK 188 You can also use the CreateFilm() method on the Film class itself to perform the same action: BookEntities ctx = new BookEntities(); Film NewFilm = Film.CreateFilm(0); NewFilm.Title = "New film2"; NewFilm.Description = "New film"; NewFilm.Length = 300; ctx.AddToFilms(NewFilm); ctx.SaveChanges(); Notice how in the previous example we created a film with ID 0 that EF automatically incremented when we saved it back to the database. Entities can be customized by using partial classes. So in the previous example you might want to add some new methods to your Film entity. This could be achieved as follows: public partial class Film : EntityObject { public void CheckAvailability() { } public void PrintTicket() { } } Updating To update an EF object, simply retrieve an entity, make your changes, and then call the SaveChanges() method on the DataContext: BookEntities ctx = new BookEntities(); Film FilmToUpdate = ctx.Films.Where("it.FilmID = 3").First(); FilmToUpdate.Title = "New updated title"; ctx.SaveChanges(); CONCURRENCY EF supports a number of different concurrency options. The default is optimistic concurrency (last write wins). Other advanced concurrency options enable EF to check if underlying data has changed before writing it back. Deleting Deleting entities is very easy. You must remember however to delete related child objects if referential integrity is enforced in your database (note the example database doesn’t enforce referential integrity to make it easier to play with). CHAPTER 8  ENTITY FRAMEWORK 189 BookEntities ctx = new BookEntities(); ctx.Films.DeleteObject(ctx.Films.Where("it.FilmID = 5").First()); foreach (FilmShowing fs in ctx.FilmShowings.Where("it.FilmID = 5")) { ctx.FilmShowings.DeleteObject(fs); } I hope you now have a basic idea of what EF can provide for you: ctx.SaveChanges(); EFv1 Criticisms ORM frameworks are a subject many people feel strongly about and EF received a huge amount of criticism when it was first released. A number of developers even set up a petition website entitled “ADO.NET Entity Framework vote of no confidence” to highlight to Microsoft their concerns about Entity Framework’s design. The criticisms are well worth a read and can still be viewed at http://efvote.wufoo.com/forms/ado-net-entity-framework-vote-of-no-confidence/. The main criticisms most have of EFv1 are that • EF is too focused on the data aspects of an ORM framework and neglects other areas, for example, validation and transactions • No support for persistence ignorance (EF is too tightly coupled to the underlying data store) • EF has too many dependencies and lacks the ability to create entities as standard .NET classes (you will hear this referred to as POCO or plain old CLR objects) • Lack of support for lazy loading • Difficult/unsatisfactory methods to add domain logic to entities (currently this has to be carried out by creating partial classes) • The EDM is held in a single file, which creates a bottle-neck for source control in multi-user environments • Immature tooling support, which sometimes mangles model files or will not open when customizations to raw models are made While there are workarounds to some of these issues, such as lazy loading and persistence ignorance, it was evident that these areas would need to be addressed for EF to gain the acceptance Microsoft hoped for. Entity Framework 4 The EF team was determined to make the next version of EF an excellent ORM solution, so it formed an advisory panel that included well-known experts, such as Martin Fowler (patterns) and Eric Evans CHAPTER 8  ENTITY FRAMEWORK 190 (domain-driven design). I believe this release has resolved a number of the original concerns and introduced some great new features. Let’s see what they changed. EDM Designer Changes VS2010 contains a new Model Browser window that allows you to easily navigate your EDM (Figure 8-10). It is worth noting that previously in EF if an entity was removed from the model and subsequently brought back by using the wizard's update model functionality, then it would not be recreated. This was because a reference to the original object was still held in the CSDL file, so EF believed it still existed. In VS2010 the Model Browser window now contains a new facility that allows you to remove the CSDL entries as well. To do this, simply right-click on the item you want to remove under the Store node and select Delete. This will then remove the entity from the storage model. Figure 8-10. New model browser window . see what they changed. EDM Designer Changes VS 201 0 contains a new Model Browser window that allows you to easily navigate your EDM (Figure 8- 10) . It is worth noting that previously in EF if. BookEntities(); Film NewFilm = Film.CreateFilm (0) ; NewFilm.Title = "New film2"; NewFilm.Description = "New film"; NewFilm.Length = 300 ; ctx.AddToFilms(NewFilm); ctx.SaveChanges();. to the original object was still held in the CSDL file, so EF believed it still existed. In VS 201 0 the Model Browser window now contains a new facility that allows you to remove the CSDL entries

Ngày đăng: 01/07/2014, 21:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan