none
WPF, MVVM , Entity Framework: Is there an example to show how Entity Frameowk work with MVVM pattern?

    Question

  • Is there an example to show how Entity Frameowk work with MVVM pattern or WPF?
    Does it suppose to be the Model layer implement LINQ to Entities?
    Thx!

    Wednesday, September 23, 2009 12:49 AM

Answers

  • 1)  Linq to Sql was the first LINQ/database framework from Microsoft.  LINQ to Entities is the ADO.NET Entity Framework, and is the newer framework being developed.  It has many advantages, including supporting databases other than MS SQL, and also is the one that's getting nearly all of Microsoft's development efforts (ie: it's improving dramatically in .NET 4 - new features are being added, etc).  If this is new development, I would recommend using EF.

    2) Using Entity as Model has 1 (very large) advantage - it's simple.  Using Entity as DAL is more complex, but makes it easier to:
    • Extend the default validation, ie: put your own custom validation in place
    • Change ORM technologies in the future (ie: in 5 years, if you want to move away from EF to something else, it's easier if you don't have this coupled to your main logic)
    • Work with being able to completely regenerate the entity layer at any time, and still have custom code handled easily

    Reed Copsey, Jr. - http://reedcopsey.com
    Monday, September 28, 2009 5:25 PM
  • I think Reed is correct when he says:
    • "Using Entity as DAL is more complex, but makes it easier to: Extend the default validation, ie: put your own custom validation in place" see here for an example how to achieve this!
    • "Work with being able to completely regenerate the entity layer at any time, and still have custom code handled easily" thanks to partial classes (as is the case above) you shouldn't have any problem deleting and regenerating the model at any time.
    • Marked as answer by JJChen Thursday, October 01, 2009 12:58 PM
    Monday, September 28, 2009 8:46 PM

All replies

  • I don't know of a specific example combining the EF technology with the MVVM pattern, however...

    Entity Framework would really not "intersect" with MVVM code, in any tangible way.  The EF code is really all tied to the Model in M-V-VM.  MVVM is about interaction between the model and "other layers", in this case, the View (for presentation) and the ViewModel (for control).

    Since the EF code is really entirely in the model, and not part of the visual representation of that model, it's a separate issue.  You should be able to use any MVVM article for discussion of MVVM, and any EF article for learning about EF.  EF is all within the Model, so there shouldn't be too much confusion.

    However, there are some really great nuggets of wisdom in this alt.net discussion , in particular, read Glenn Block's responses.  He gives some valuable guidance, and some specifics on why you don't want to let the EF code "pollute" your ViewModel (basically, keep EF in the Model, not the View/ViewModel).

    Reed Copsey, Jr. - http://reedcopsey.com
    Wednesday, September 23, 2009 12:56 AM
  • Hi JJChen!

    May be this can help you! It's not exactly what you were asking for, but it may give you some hints!
    Monday, September 28, 2009 10:58 AM
  • Thanks for Reed and Savvas for the information.

    We are new to the Entity Framework.
    There are two questions bother us:

    1) Should we use LINQ to Entities or LINQ to SQL?
        Savvas mentioned the example use LINQ to SQL.
        When we read articale which comparing Entity Framework with LINQ to SQL. It seems that Entity Framework is better than LINQ to SQL.
        LINQ to SQL provides very limited mapping capabliites.

    2) Should we use Entity as DAL (Data access layer) or directly as model layer?
        In our prototype, we used to use XML files as storage. We use LINQ to XML to loading/saving data.
        We create Model layer with some validation logics related each properties.
        If we use generated entity classes as model layer, how could we hook up the validation logic in?
        Since we do not want to override the generated entity classs's code in case you need regenerated them as database schema changes.

    Thanks,
    Jane
    Monday, September 28, 2009 4:25 PM
  • 1)  Linq to Sql was the first LINQ/database framework from Microsoft.  LINQ to Entities is the ADO.NET Entity Framework, and is the newer framework being developed.  It has many advantages, including supporting databases other than MS SQL, and also is the one that's getting nearly all of Microsoft's development efforts (ie: it's improving dramatically in .NET 4 - new features are being added, etc).  If this is new development, I would recommend using EF.

    2) Using Entity as Model has 1 (very large) advantage - it's simple.  Using Entity as DAL is more complex, but makes it easier to:
    • Extend the default validation, ie: put your own custom validation in place
    • Change ORM technologies in the future (ie: in 5 years, if you want to move away from EF to something else, it's easier if you don't have this coupled to your main logic)
    • Work with being able to completely regenerate the entity layer at any time, and still have custom code handled easily

    Reed Copsey, Jr. - http://reedcopsey.com
    Monday, September 28, 2009 5:25 PM
  • I think Reed is correct when he says:
    • "Using Entity as DAL is more complex, but makes it easier to: Extend the default validation, ie: put your own custom validation in place" see here for an example how to achieve this!
    • "Work with being able to completely regenerate the entity layer at any time, and still have custom code handled easily" thanks to partial classes (as is the case above) you shouldn't have any problem deleting and regenerating the model at any time.
    • Marked as answer by JJChen Thursday, October 01, 2009 12:58 PM
    Monday, September 28, 2009 8:46 PM
  • Reed & Savvas,  thanks again for the information and clarification.

    So far we plan to use the Entity as DAL.
    This means we will handle the synchronization between our Model layer with entity framework's entity layer.
    when collection changes in our model layer, it will update the entity framework's entity layer.
    So when we call context.SaveChanges(), it will update database as well.

    We plan to use Microsoft SQL server compact 3.5 as our database provider.
    Do you know there is any limitation for using Entity Framework with SQL compact database?
    After we generate Entity Data model (EDM) base on SQL compact database,
    we do not see any Navigation Properties generated in EDM.
    This means there is no any collection generated in EDM.
    Not so sure it causes from our database tables themselves or SQL compact database itself.
    Thx!

    Wednesday, September 30, 2009 1:23 AM
  • Hi JJChen,

    I don't think there's limitation would cause such problem. Please check out this Walkthrough , and see if you can generate all things expected successfully.

    Best regards,
    Bruce Zhou
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    • Marked as answer by JJChen Thursday, October 01, 2009 4:06 PM
    • Unmarked as answer by JJChen Thursday, October 01, 2009 4:33 PM
    Thursday, October 01, 2009 7:38 AM
  • Hi Bruce,

    Thanks for the info. We do not have problem to generate Entity Data Model from a compact database.
    The problem is that we did not set up the relation tables correctly. That is why Entity Data Model does not show any ralationship between each entity yet.
    Thx!
    Jane
    Thursday, October 01, 2009 12:58 PM
  • Hi Bruce,

    In the above link you provide, we see all examples using "Using" statement
    using (NorthwindEntities nwEntities = new NorthwindEntities())
        {
          IQueryable<string> customers =
             from c in nwEntities.Customers select c.Company_Name;
    
          foreach (String c in customers)
          {
            Console.WriteLine(c);
          }
       }
    

    So we do not need to worry about Dispose problem.

    In realy world, we may need to reference this Entities (i.e. nwEntities) in whole application system.

    So we want to create one instance and share it with the whole application system.

    Question is do we need to explicitly handle the Dispose the "Entities" instance?
    such as "Entities" = null in the Dispose function.
    Thx!

     

    Thursday, October 01, 2009 4:13 PM
  • Yes.  If you use the entities, and plan to keep them alive for the entire program duration (which, btw, is problematic), you should explicitly Dispose of the entities when you are finished (ie: when your main window closes, at a minimum).

    You'll want to actually Dispose the entities, not just set them to null.  This will look something like:


    nwEntities.Dispose();


    Anything you see in the examples that is wrapped in a using statement should have Dispose() called on it when you are finished, if you are not using a "using" statement.



    Reed Copsey, Jr. - http://reedcopsey.com
    Thursday, October 01, 2009 4:44 PM
  • Hi JJChen,

    Reed is right, if you plan to use the Entities in the whole application, you may define the Entities object as a class member, and construct its instance using singleton design pattern.  Before the application terminates, you need to call the Dispose method explictly to release resources.


    Best regards,
    Bruce Zhou
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Friday, October 02, 2009 12:36 AM
  • Hi Reed and Bruce,

    From your information, it look like it is not good idea to keep Entities alive for the entire program duration.

    What are the problem your guys see?

    What is a good practice to handle it in general?

     Whenever needing to load/save data, create a new instance and do the job and dispose it.

    We do need to keep event log in database, in our case, we seem need to constant save event log data into Database.

    That is one reason we think we need the instance of Entities all the time so we can keep synch entities and our data model layer.

    Thx again!

    Friday, October 02, 2009 12:53 AM

  • Hi JJChen,

    No, that depends on your requirement. Suppose if your application will use Entities object in many places, it's a good idea to hold an instance of Entities object in the application life cycle which could improve peformance. This is because constructing new Entities object evertytime is an expansive operation.


    Best regards,
    Bruce Zhou
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Friday, October 02, 2009 1:15 AM
  • We have new question coming up and still related to the MVVM & Entity Framework (EF).

    We try to use EF generated Entity layer classes as our Model layer classes.
    Before we implement some INotifyPropertyChanged in some model classes.
    So if property changes, we can raise OnPropertyChange to notify View to reflect property changes.

    Right now, when we use EF generated entity classe, it does not include OnPropertyChange in its "set" property.
    We try to use the partial class to handle it, it requires add a lot of code to do that.
    In a partial class to response to the "On'Property'Changed" to raise OnPropertyChange(), such as OnIsActiveChanged() event

    Is there a way we can tell EF during generate Entity class to add OnPropertyChange in its set property operation?
    thx!

    Here some links we found:
    http://msdn.microsoft.com/en-us/library/bb738612.aspx
    http://msdn.microsoft.com/en-us/library/cc716747.aspx

    Entity Framework FAQ: http://blogs.msdn.com/dsimmons/pages/entity-framework-faq.aspx
    Thursday, October 08, 2009 9:47 PM
  • Question: where to put DataAccessLayer?

    here is a link discuss this: http://stackoverflow.com/questions/1717621/mvvm-where-to-put-data-access-layer 

    Some comments as following:

    Model - I think of the Model as the state of the system. It provides an interface to the data, and it keeps track of system status. The Model does not know about the ViewModel or View--it just provides a public interface to its data and various events to let the consumers (usually ViewModels) know when the state has changed.

    ViewModel - The ViewModel is in charge of organizing or structuring all the data needed by the View, keeping track of the status of the view (such as the currently selected row of a data grid), and responding to actions on the view (such as button pushes). It knows what the view needs, but it doesn't actually know about the view.

    View - The View is the actual look and feel of the UI. It contains all the built-in and custom controls, how they arranged, and how they are styled. It knows about the ViewModel, but only for the purpose of binding to its properties.

    Gateway - This is the part that directly addresses your question. The Gateway (which is basically my way of saying "DataAccessLayer") is its own separate layer. It contains all the code (including LINQ queries) to CRUD or select, insert, update, and delete data from/to your data source (database, XML file, etc.). It also provides a public interface to the Model, allowing the Model to focus on maintaining system state without having to concern itself with the details (i.e., the queries) needed to update the data source.

    DataAccess Classes - In C#, these are very simple classes that model your elemental data objects. When you select something using a LINQ query, you will usually create an IEnumerable<T> or List<T> where T is one of your data objects. An example of a data object would be:

    The big advantage of a design like this is that it really separates your concerns. Everything has a specialized job, and it's (usually) pretty easy to know what kind of thing goes where.

    The disadvantage is that it may be overkill for small projects. You end up creating a lot of infrastructure for public interfaces that basically pass a single wish through several layers. So, you might end up with a scenario like this: [user clicks Submit, ViewModel tells Model to AddNewPerson, Model tells Gateway to InsertPerson] instead of a scenario like this [user clicks Submit, ViewModel adds new record to the database directly].


    JaneC
    Saturday, December 18, 2010 8:40 PM
  • Here is usefule information in WPF application Framework (WAF)  http://waf.codeplex.com/wikipage?title=Architecture%20-%20Get%20The%20Big%20Picture&referringTitle=Home

    Architecture – Get The Big Picture

    1. Introduction

    This document describes a concrete example architecture for .NET/WPF Rich Client Applications. This architecture doesn’t claim to be the preferable solution in every scenario but you might find the one or other part described here useful for your own software systems.

    2. Layered Architecture

    Layering is a very useful tool in structuring object-oriented software systems. It helps to organize the types and namespaces into a large-scale structure. The layered architecture defines a few rules to ensure that the structuring is done right. One of the rules says that “lower” layers are low-level and general services, and the “higher” layers are more application specific. This way you are able to divide the software artifacts with related responsibilities together into discrete layers. Another rule says that “higher” layers call types of “lower” layers, but mustn’t vice versa. This rule helps to reduce the coupling and dependencies between the types and so increase the reuse potential, testability and clarity of the software system.

    When a team agrees to use a layered architecture then it has to choose one of the hundreds hardly distinguishable layering schemes found in books about software design and architecture. When you are interested to dig deeper into the different layering schemes then you might start with the book Patterns of Enterprise Application Architectures [Fowler03]. I personally prefer the layering scheme shown in Larman’s book Applying UML and Patterns [Larman04]. Figure 1 shows this layering scheme which I have adapted to reflect the .NET/WPF platform.

    layered-architecture.png

    3. Guidelines for a Layered Architecture

    1. General vs. Application Specific Types
    Separate the types into the different layers. Put the low-level and general service types into the “lower” layers, and the more application specific types into the “higher” layers. This rule is shown by the “more app specific” arrow in Figure 1.

    2. Dependencies
    The characteristic of a layered architecture is that “higher” layers call upon services of “lower” layers, but mustn’t vice versa. This way we avoid circular references between types of different layers and we decrease the number of dependencies. This guideline can be seen by the “dependency” arrow in Figure 1.

    3. Applicability
    A result of the first and second guideline is that “lower” layers are more reusable than “higher” layers. Figure 1 shows this via the width of the UML packages and the “With implies range of applicability” arrow.

    4. Relaxed Layering
    This is also known as layer skipping. Relaxed Layering means that layers are allowed to call layers deeper than the one directly below them. By example a view in the Presentation layer can bind a text box to a property of a business class from the Domain layer.

    5. White-box reuse
    A class is allowed to inherit from a class defined in a lower layer. The same is true for implementing interfaces. However, white-box reuse tightens the coupling between the layers and should be avoided whenever possible. One of the object-oriented design principles in the book Design Pattern [GHJV95] is “Favor object composition over class inheritance”.

    6. Namespaces
    The layer name might be a part of the namespace. A common naming scheme for namespaces is: [Company].[Product].[Layer].[SubSystem]
    Example: Microsoft.Word.Presentation.Ribbon, Microsoft.Outlook.Domain.AddressBook

    Tip 1: Avoid the name “Application” inside the namespace because the base class of App.xaml is also named “Application”. Therefore, I use the name “Applications” inside my namespaces to refer to the Application layer.

    Tip 2: Avoid assemblies that contain types from different layers. When every assembly is associated with just one layer then you gain the advantage that assembly references don’t allow cyclic dependencies. This way the compiler helps you to ensure that the dependencies are from “higher” to “lower” layers. Furthermore, the “internal” access modifier restricts the access to the types inside the same layer. I believe that you should avoid accessing “internal” types or members over layer boundaries.

    4. Presentation Layer

    This layer is responsible for the look and feel of the application. It contains the WPF views, user controls, custom controls and resources, styles, templates, etc. ValueConverters are also common in this layer especially when they convert data from lower layers into WPF objects (e.g. Convert an enum value into a ImageSource). Besides the WPF Framework you might use further technologies for reporting, audio output, speech interface, etc. The code which interacts with these technologies might also be a good candidate for the Presentation layer.

    Common Issues
    1. Implementing business logic in the Presentation layer instead of the Domain layer.

    2. Implementing the UI workflow in in the Presentation layer instead of the Application layer.
    Example: The click event handler of the Options button creates and shows the Options window.

    3. Implement validation logic in the Presentation layer instead of the Domain layer. The Presentation layer is only responsible to trigger the validation when the user changed a value. When the validation fails the Presentation layer has to show a user-friendly message.

    Automated Testing
    The Presentation layer is difficult to test because the own code is tightly coupled with the WPF Framework. Two common approaches for testing this layer are:

    • Automated UI testing with the UI Automation Framework which is well supported by WPF. With this Framework you are able to simulate user interaction and you can track the reaction of your application.
    • Writing unit tests for your Presentation layer code. In this case you should emulate the behavior of WPF to test your code in a realistic environment. This can be tricky because WPF uses the Dispatcher threading subsystem.

    5. Application Layer

    The Application layer is responsible for the application workflow. A common way to model a static workflow is done with Controller classes. In this case you might have an ApplicationController which is initialized during the start-up sequence. When a program function is triggered the ApplicationController might delegate the process of this function to a use case controller.

    This layer has the same width as the Presentation layer in Figure 1. The width implies the range of applicability of the layer. Thus, the Application layer is not more reusable than the Presentation layer. This is because the layer is not completely independent of WPF and so it cannot be reused in other application types (e.g. Web Application). Common WPF types found in the Application layer are

    • ICommand interface - Command Pattern
    • WeakEventManager class - Weak Events
    • Dispatcher class - Synchronization with the UI Thread

    However, even if it’s not totally forbidden to use a type of the WPF Framework in this layer you should avoid using other types as the ones mentioned above.

    Because the layer is weakly coupled with the WPF Framework you are not able to reuse this code with another Presentation technology (e.g. ASP .NET). I don’t believe that this is a real issue because the application workflow often depends on the Presentation technology. By example, desktop applications use mostly different workflows than web applications. In such a case we would have to write two different implementations of the Application layer anyway.

    The motivation of this layer is to separate the UI from the workflow concerns. The introduction of the Application layer should improve the testability and maintainability of software systems.

    Common Issues
    1. Implementing business logic in the Application layer instead of the Domain layer.

    2. WPF types are implemented or used within the Application layer although they belong to the Presentation layer (e.g. Window, UserControl, Control, Resources, Styles and Templates). This often reduces the testability of this layer.

    3. Assembly references you shouldn’t find in this layer:

    • PresentationFramework
    • System.Drawing
    • System.Windows.Forms

    Automated Testing
    This layer should be designed in a way that you are able to unit test the code. It shouldn’t contain unit testing barriers like the Presentation layer does. If unit testing cannot be done with less effort you might review the design of your Application layer.

    6. Domain Layer

    The domain layer is responsible for the business logic and only for the business logic. It’s essential to separate the concerns in this layer because in my experience the business logic is more than complex enough for itself without mixing it with other aspects. By example, any UI specific code here would break the principles of the layered architecture.

    Another reason why you should separate the concerns in this layer is shown by Martin Fowler: “Since the behavior of the business is subject to a lot of change, it’s important to be able to modify, build, and test this layer easily. As a result you’ll want the minimum of coupling from the Domain Model to other layers in the system. [Fowler03]”

    Unfortunately, the separation of concerns isn’t that easy to follow with data access strategies. Ideally, a developer working in the domain layer shouldn’t care about how the data is stored in a database or a XML file. The separation of business logic and data access strategies is also known as Persistence Ignorance (PI) or Plain Old CLR Objects (POCO). Modern persistence frameworks try to support this concept but all of them come with some modeling limitations for business objects. Therefore, you should decide which data access strategies you are going to use before starting to model the business rules.

    Software systems mostly need some kind of validation to ensure that the business logic has to deal with correct data only. These validation rules are defined by the business model and so the Domain layer is the right place to implement them. Just keep in mind that you don’t start to duplicate the validation code between the business objects.

    Common Issues
    1. The validation logic code or the business logic code is duplicated in other layers. By example you have implemented a custom WPF ValidationRule which contains the same validation logic than the business class.

    2. You can’t unit test the business logic decoupled from the data source. By example you have to set up a database with predefined test data when you write unit tests for your business logic.

    3. Assembly references you shouldn’t find in this layer:

    • PresentationFramework
    • PresentationCore
    • System.Drawing
    • System.Windows.Forms

    Automated Testing
    The domain layer is the heart of your application. In this layer you have the code which is important to your customer. Your customer is seldom interested to get a polished fancy user interface but he is paying attention on how you have modeled his problem domain.
    That said I believe writing unit tests for your business logic is essential to guarantee a high quality software system. Unfortunately, some persistence frameworks make unit testing isolated from the data source very hard. This has a negative impact on time and effort to write all the unit tests for your business logic. I would consider this point when choosing a persistence framework for your application.

    7. Business Infrastructure Layer

    The Business Infrastructure layer contains reusable services which are domain specific. The difference to the Domain layer is that the types of this layer can be reused in other software systems whereas the Domain layer is designed only for the system it’s created for.

    Examples

    • Currency Converter

    8. Technical Services Layer

    The Technical Services layer contains “high level” services which are independent of the business. These services are mostly part of a reusable library or a Framework.

    Examples

    • Persistence Frameworks (e.g. ADO .NET Entity Framework)
    • Validation Frameworks (e.g. System.ComponentModel.DataAnnotations)

    9. Foundation Layer

    The Foundation layer is the most depended-on layer because all layers can use types of this layer. Therefore, it has to be more stable than the other layers. Stable means in this context that existing public members aren’t changed in signature and in their behavior.

    Examples

    • Collection classes (e.g. List<T>)
    • Logging (e.g. TraceSource)

     


    JaneC
    Saturday, December 18, 2010 8:54 PM
  • our application is a window application whch uses WPF, MVVM pattern, Entity framework 4, data stroage contains both SQL server compact edtion and xml files.

    We treat entity data model generated entities (we call EF-entities) as data model layer

    Since the whole application is running in single PC with limit pc power. We do not care decoupling like web application (separating client application with server application and use WCF service between client app and server app and pass POCO or DTO through WCF service. ViewModel only references DTO). In our case, our application is pretty small and we do not want to instruduce more layer to complicate it. So we directly reference EF-entities in Viewmodel layer 

    Data access layer which includes CRUD (CreateNewCustomer, UpdateCustomer, DeleteCustomer, GetCustomers(). etc). It will reference EF-entity such as Customer in the class like IEnumerable<Customer> GetCustomers()

    Inside the Data access layer it will call Entity framework ObjectContext to query or update data by using Link to Entity (In our case, we combine DataAccess layer and DataAccess class describe in above) into one class called DataAccessLayer.

    We have draw a layer diamgram to descibes our layer architecut in which (bottom up)

    1) database links to Entity data model which includes EF-entities

    2) Data Access layer depends on the Entity data model (includes EF-entities class).

    3) ViewModel references the DataAccesslayer to get collection of customers and bind to view in listbox.

    ViewModel also directly referece EF-entities.

    During our design review of application architecture, other group developers start question us

    Should the Model layer depend on Database access layer? or should Data access layer depends on model layer?

    In our case, we want to answer Data access layer depend on model layer.

    Today we went the RockStars events in Microsoft store in Mission Viejo (California). One of speaker mentioned that Entity Data model is data access layer.

    So in genearal, should we treat entity data model as data access layer or should we treat entity data model as model layer?

    Or Entity data model play both model and data access layer roles?

     

     

     


    JaneC
    Monday, April 11, 2011 4:54 AM
  • reference another thread: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/2fda1bd8-5010-4ecd-bb4b-1abb6d426136

     Entity Data Model is DAL (Data access layer). EF-entities are objects in the DAL.

    What we create Data access layer is the Data service layer which wrap the DAL layer and provide interfance for CRUD. Normally, Data service layer (such as WCF service) will user DTO and not directly reference the EF-entities.  


    JaneC
    Friday, April 15, 2011 1:06 AM
  • There is a good article "Objects and Art of data modeling" in MSDN magazine

    http://msdn.microsoft.com/en-us/magazine/hh456393.aspx

    CodeMaganize (Jan-Feb 2012) introduces "CODE Framework: Writing MVVM/MVC WPF Application"   http://www.code-magazine.com/Article.aspx?quickid=1201061 

    "CODE Framework" is free: http://codeframework.codeplex.com/

     

    Good and Simple MVVM explained by Jeremy Iikness (mention Navigation & MEF)

    http://www.wintellect.com/cs/blogs/jlikness/archive/2010/04/14/model-view-viewmodel-mvvm-explained.aspx


    JaneC



    • Edited by JJChen Saturday, February 25, 2012 2:06 PM
    Wednesday, December 14, 2011 7:06 AM
  • HI,

    UP, What is the right pattern?

    Best,

    WP

    Sunday, September 23, 2012 11:50 PM