Using the Entity Framework in a Layered Architecture

    My July 2008 Data Points column was just released on the MSDN Magazine web site. This month I demonstrate how to use the Entity Framework in a multi-tiered architecture passing entities through the layers via WCF. The code sample is available from their web site too.

    The Entity Framework has been a much discussed topic of late. Many articles discuss and show how to build different types of models and facets of the Entity Framework. This article shows one way to integrate the Entity Framework’s models into an application that uses layers and a form of the MVP pattern.

    2008-07-MSDN

    #1 Dew Drop - July 4, 2008 | Alvin Ashcraft's Morning Dew on 7.04.2008 at 5:07 PM

    Pingback from Dew Drop - July 4, 2008 | Alvin Ashcraft's Morning Dew



    #2 Martin on 7.14.2008 at 6:35 AM

    Hi john

    I hope you can help

    I have WCF that uses EF and is being referenced in Silverlight.

    When the Reference is generated a

    System.Runtime.Serialization.DataContractAttribute( IsReference=True)

    is inserted into the Reference.cs file .

    I have one object that is EF.

    I can not get the app to compile while the IsReference-=true is there.

    the message is"Error 297 'System.Runtime.Serialization.DataContractAttribute' does not contain a definition for 'IsReference' "

    I can delete this and it compiles fine but I am then having inconsistancies in the serialized objects coming back intact.

    Any and all help appreciated, I can't believe that I am the only person with this issue.

    Thanks

    MartinTr



    #3 keith patton on 7.17.2008 at 9:03 PM

    isreference is only supports on clients which have .net 3.5 SP1 (or currenlty the beta). See blogs.msdn.com/.../561188.aspx for a workaround (check the comments too for teh update on the knowne issue which requires a furter workaround). it took us a few days to work this out for .net 3.0 clients of a .net 3.5 SP1 Beta WCF service backed onto EF.



    #4 Andrey Nikulin on 8.06.2008 at 10:16 AM

    Hi John,

    Great article. Thanks. But unfortinately I cannot find NorthwindEF database to try example. Where I can find it?

    Thanks



    #5 Braulio on 8.23.2008 at 2:28 PM

    Hi John,

    Could you post a sample using Silverlight as UI Layer?

    It seems that ADO .net Entity Framework does not behave well with Silverlight Beta 2 (having SP 1 installed).

    Some chaps says that it is an installation issue, some others that is just a bug :-(.

    Thanks in advance

    Braulio



    #6 John Papa on 8.23.2008 at 5:56 PM

    Braulio & Martin ... Keith is correct. For now if you run .NET 3.5 with SP 1 and Silverlight 2 Beta 2 you need to remove the IsReference property settings from the attributes. These are in the generated class file. This of course is not a long term solution since the classes are generated and could overwrit ethis change. I am hearing that Silverlight 2 will have a patch or update of some sort in the near future that will recoginize the IsReference property in the attribute. Once this happens all will be well. But for now, you can manually remove the IsReference property setting. Its the downside of being bleeding edge :-)



    #7 Frank on 9.05.2008 at 10:03 AM

    Hi John,

    In this article, you mentioned that the MVP pattern would work with Silverlight. However, if you try to reference the NWPresentation project in a Silverlight project, the assemblies would not be compatible. In order for the NWPresentation project to be fully abstracted (compatible w/Silverlight, WPF, ASP.Net etc.), would you recommend creating this as a Silverlight class library?

    Frank



    #8 John Papa on 9.05.2008 at 10:10 AM

    Frank ... Actually I have had quite a few questions via email on using MVP with Silverlight 2. Instead of answering them as they come in I plan on putting a blog post on my site that explains how to morph my example in the MSDN article to work for Silverlight (the article space was just too limited to get into it there). In the meantime, yes, the code could be converted to work as a Silverlight class library. I’ll explain more once I get the post up :-)



    #9 Fred on 10.09.2008 at 1:59 PM

    I loaded the code for your July 2008 DataPoints article, downloaded and installed the NorthwindEF database, installed the new stored procs using the provided script, but when I compile (Rebuild All), it flags anything that depends on "using NWModel;" with a compile error.

    The only way to compile the code cleanly is to comment out that line in several places and replace it with "using NWLibrary;". Did you switch gears at some point during the project and forget to change all the references from NWModel to NWLibrary?

    Even after setting the default start up project to NWUI (as delivered the project doesn't point to NWUI) and starting in debug mode, when I type in the letter "D" (or lower-case "d") in the search box, the LINQ query stalls for several minutes and never returns anything. No error is displayed.

    I fired up LINQPad and put the following into it and it returned three rows, so I know the database is there:

    from c in Customers

    where c.CompanyName.StartsWith("D")

    select c

    Environment: Windows XP SP3, VS Team System 2008 Development Edition SP1, .Net Framework 3.5 SP1, SQL Server 2008 Developer Edition.

    Do you have any suggestions to get your example to run correctly in my environment?



    #10 Peter on 11.26.2008 at 1:43 PM

    Can you blog any post how implement MVP in asp.net 3.5? or asp.net MVC?



    #11 Colin on 12.23.2008 at 6:13 AM

    Hi John,

    Thanks for the article it's great! One question and I might sound silly here but how could this strategy be modelled to allow the NWModel to be replaced in situations where you might be developing for Oracle and SQL Server? i.e. the Model is pluggable for different data sources and we don't have to create all the services etc again when referencing a different model.

    Thanks

    Col



    #12 Leon on 12.29.2008 at 12:06 PM

    Hi John,

    in this example, you are using the Windows Communication Foundation (WCF) to connect the presentation layer to the Services. Although i have not done much with WCF, i guess this technology was initially intended to be used in cases where you have a real 'n-Tier'-Application, where layers are physically detached.

    So how would your example application look like, if the target would have been a classic WinForms application, where layers are mainly used to get a clear and maintainable architecture?

    Does the presentation layer (UI and presentators) now have to reference the EDM directly, because there is no more "fascade" for the Entity-Classes through WCF?

    To me it seems as you are using WCF to wrap up the original entitys, so that the presentation layer only references them through a circuit.

    Best regards from Germany,

    Leon



    #13 John Papa on 12.29.2008 at 12:44 PM

    Hi Leon,

    If you mean WinForms application where its a single tier, meaning all the code is in a single executable including all data access, then yes ... you would exclude the WCF code entirely and just have the presenter talk to the middle layer services. I generalyl would not have the presenter talk to the EDM directly though. I would still crate a service layer (manager layer, whatever we want to call it) that the presenter talks to. The service layer handles the calls to the EDM. Its part of the single responsibility principal to have classes and layers in general handle a single role. Just my style :)

    If the application is spread across multiple physical machines, using WCF is a solid technique. WCF is eing used to talk from the client computer to the server computer, where the remote services live, in my sample application. The entities have to be transported to the client somehow, so WCF handles this for us.

    Hope this helps!



    #14 Leon on 1.02.2009 at 3:08 PM

    Hi John,

    thanks for your fast and detailed answer, it gave me most of the information I needed.

    Nevertheless, I am not sure what kind of objects are the best choice to represent the entitys in the higher layers such as UI, Presenters or the Services.

    Since those Layers should not reference the EDM directly, there must be some replacements for them ("DataTransferObjects"), so that data can be routed through those layers up to the User Interface, and the layers know with what kind of data they are dealing with. (e.g. List<Customer>).

    However, creating various "dummy classes", which contain the same properties as the original entity-classes in the EDM seems a little bit painful to me.

    As i mentioned in my first post, I am not using WCF, so the entity aren not "hidden" through some kind of DataContract.

    So what solution would you favour to inform the uper layers about the composition of the entities used for transferring data?

    kind regards,

    Leon



    #15 John Papa on 1.04.2009 at 11:16 AM

    Leon, Most applications I work on are split out physically so I need WCF or something similar for services. However, if you are not passing across physical machines, you can references the entities directly if you want to. Otherwise, if you want a clean logical split without using a WCF or something similar then you can have you business layer return DTO's as you suggest. The business layer can query the EDM and its model, then populate DTO's to pass to the upper logical layers. So there are a few options you can follow.

    The DTO approach is a fine one. If you use M-V-VM (Model-View-ViewModel) then the DTO is sucked into the ViewModel. The V is bound to the VM, so its irrelevant what shape the model takes in the upper layers with this pattern.

    There are other good choices too, but I would stick with something that gives you good separation of responsibilities like this.



    #16 John Papa on 1.04.2009 at 11:21 AM

    Colin, that gets very tricky. Different DB models means that you have 2 EDMs. Consider that each DB schema creates different storages data in the EDMX file. So Oracle schema and SQL Server schema creates different XML, which means you really need 2 EDMX files (2 EDMs ... 2 models).

    With the 2 models you could create interfaces that matches both models (an interface for the Patient entity from Oracle and from SQL Server, for example). Then you could abstract away where the entity came from. Its a pretty deep topic and the best way I can help is probably with a face to face. Short of that, I highly recommend Julie Lerman's EF book that is coming out. She knows this stuff cold and has written down some awesome deep material like this in her book.



    #17 John on 2.16.2009 at 9:54 PM

    Great article John :) I do have a question though. What if WCF is not an option given the case of an application on the desktop accessing a local data store. How do you serialize your objects without WCF? I've been playing around with the DataContractSerializer, but it still yields child objects i.e. Customer.Ordrers that have EF ObjectContext goo (EntityCollection), rather than a clean generic List. Thanks!



    #18 Dave on 6.10.2009 at 4:24 PM

    Could you provide an example of an ASP.NET application accessing the Presentation layer? Do I need to add a WCF service reference in the web app? I wouldn't think so since the WCF service is defined in the Presentation layer.

    Thanks.