text: <<
  Very nice article!
  Is there a way to serialize a department with employees using wcf without modifying Model.tt to add [KnownType(typeof(Employee))] and what not?
  Hi Stefan,
  The KnownType attribute allows you to specify types that should be included for consideration during the deserialization. It’s typically used when the declared type for the information to be transmitted is a base class or an interface and the receiving endpoint cannot determine in advance which type is actually sent:
  In this case, where you have a Department type and an Employee type that are not really related to each other when it comes to the class hierarchy, it’s not necessary.
  You can choose to distribute the assembly that contains the entity classes to any client application that consumes the WCF service or create DTOs (Data Transfer Objects) that represents the data to be serialized and then map these to the entity objects. If you add a service reference in Visual Studio (VS) you can uncheck the CheckBox that says “Reuse types in referenced assemblies” in order for VS to generate the DataContracts.
  Keep in mind that data contracts should only ever contain data and not any behaviour as the message being passed between the client and service is a pure text-based serialized message.
  Hi Team,
  It is really nice example to learn. But when i follow the same steps. I am getting few errors. Can you provide us the zip file of this source code which we can compare with & find out our mistakes ?
  Very Nice Article here… But one question if you can answer…
  In the Console Application, Do we need to write following code ?
  foreach (Employee emp in it.Employees)
  emp.EntityState = EntityState.Unchanged;
  we are changing the Department Entity (Name Property) and adding one Employee in that Department. So, Do we really require to add these line ? which just represent the existing employee state is Unchanged ? what effect it will if we do not specify this ?
  Because in real time scenario, I suppose coder (Developer) will do all above but will not take care these
  Hi Brijesh,
  As the client side code first sets the EntityState property of the Employee objects to be added to the database to EntityState.Added, you then need to change their state to EntityState.Unchanged before passing them to the business layer again. If you don’t change the state from Added to Unchanged, a duplicate record will be added to the database for each entity having its EntityState property set to EntityState.Added.
  Remember, as the article states, that the key to be able to determine the state of a disconnected entity is to have the objects track their own state by explicitly setting the state on the client side before passing them to the business layer.
  However, you could reset the state of all entities to Unchanged in the business layer or data access layer once the changes have been persisted, i.e. after the SaveChanges method has been executed.
  Great…
  You’re correct If we didn’t change the state it will add the duplicate entry as the last state is added. Now, Here we have sequential lines of code from where we can identify this easily & can remember or can review from previous statement.
  So, in real world application, Data may inserted/ updated from different areas or different classes/ methods/ objects. So, in that case, we can’t be sure about those right ?
  If you agreed with me, then there is only solution left is what you described in last passage that change the entitystate once the SaveChanges Method called. that means we need to include
  it.EntityState = EntityState.Unchanged instead of emp.EntityState = EntityState.Unchanged
  and this line would be just below businessLayer.AddDepartment(it); line (where we add department “IT” at the first time)
  and such every operation we need to make sure to change the status to Unchanged after completion & for that we should use business layer class
  Am I right ?
  The rule is that any client side class or method is responsible for setting the correct entity state for each entity object in the graph before calling the business layer to persist the changes.
  This means that if you don’t want an UPDATE statement to be generated for the Department object when you call the UpdateDepartment method, you should set its EntityState to Unchanged. In the sample code, I change its name to “Information Technology Department” after adding it and hence set the EntityState to Modified before calling the UpdateDepartment method.
  If you choose to reset the state of all entity objects to Unchanged in the business layer or data access layer once the changes have been persisted, you don’t need to explicitly set the state to Unchanged on the client side (foreach (Employee emp in it.Employees){ emp.EntityState = EntityState.Unchanged }) before passing the same entity to the business layer again.
  The sample code doesn’t reset the states on the server side and consequently needs to set the EntityState to Unchanged for all Employee objects that have already been persisted (added) during the first call to the AddDepartment method before calling the UpdateDepartment method.
  How to handle concurrency conflicts that may occur is out of the scope of this article. If you don’t set up EF to detect such conflicts, whoever updates the database last overwrites any previous changes.
  Thanks for your very useful article…..
  how can i download the source of the program????
  Hi Mehrsa,
  I am glad you liked the article. The code isn’t available for download at this time but everything you need to be able to follow and compile the sample solution should be found in the article.
  Very good article Magnus,
  I am, however, having an issue. I will first admit that I am new to using EF. I have created all the tiers but my solution has included only one stored procedure. This procedure does not pull all columns from a table. Instead it calls a user function. The solution is compiling okay, but when I run, I get this error:
  The type ‘my_stored_proc’ is mapped as a complex type. The Set method, DbSet objects, and DbEntityEntry objects can only be used with entity types, not complex types.
  I have searched with no luck yet and I have tried deleting the function imports and the complex types in the model browser and ran the Add Function Import utility but the error persists. I’m sure I’m just not grasping exactly what is going on. Can you point me in the right direction to solving this issue? Thank you!
  Hi Jerrico,
  The easiest way to execute a stored procedure and map the results to a custom type when you are using a DbContext is probably by using the DbContext.Database.SqlQuery method:
  using (var context = new Entities())
  {
  IEnumerable results = context.Database.SqlQuery(“EXEC spGetInfo”);
  }
  You should still be able be use function imports if you are using the database first approach though.
  For any questions about Entity Framework in general, I recommend you to ask them in the official MSDN forum for ADO.NET Entity Framework and LINQ to Entities:
  Excellent!!
  Is the code available? I´m having some issues trying to create my own set of clases, and having this code will solve all my doubts.
  Thanks!!
  Stuck at separating the classes:
  When the model.tt file is included in the Domain Model a T4 Compile error is given at line1 column 1.DynamicHost.ResolvePath(String path).EdmMetadataLoader.CreateEdmItemCollection(String sourcePath).TransformText() E:\Tangoe\Migrate\DomainModel\Model1.tt 1 1 DomainModel
  Hi,
  When i copy the model from the EF5 DAL project to the new DomainModel T4 generates a large number of errors
  starting with Line 1 and:
  I have changed the include to the edmx as you suggested in the articleGenerated.TextTransformation.DynamicHost.ResolvePath(String path)
  at Microsoft.VisualStudio.TextTemplatingGenerated.TextTransformation.EdmMetadataLoader.CreateEdmItemCollection(String sourcePath)
  at Microsoft.VisualStudio.TextTemplating.Generated.TextTransformation.TransformText() E:\Migrate\DomainModel\Model1.tt 1 1 DomainModel
  Make sure hostspecific=”true”
  by default it is false.
  HI,I am new in edimx can you help me out to resolve this error “Unable to load the specified metadata resource.” thanks
  […] also found a very comprehensive article on how to implement a generic repository pattern with the Entity Framework, but it was unable to […]
  Hi nice article, but I’m not really sure I follow this. How can the repository be generic if it is tied to the entity class generated for to the repository that your using e.g. the GenericDataRepository class is referring to the Entities class in the implementation methods of the IGenericDataRepository interface. I thought it was suppose to be generic and an abstract class so that you could build your own repository and have this as the base and build the specific methods that you would need but most of the CRUD would already be in place?
  Hi Vince,
  The GenericDataRepository class is a generic class that implements the CRUD methods and serves as the base class for the specific repositories, DepartmentRepository and EmployeeRepository. I am not sure what you mean with “the GenericDataRepository class is referring to the Entities class”.
  Hi Magnus, thanks for the reply. What I meant was that the methods in the GenericDataRepository create an Entities object when it needs to query the DB. e.g.
  public virtual void Update(params T[] items)
  {
  using (var context = new Entities())
  {
  foreach (T item in items)
  {
  context.Entry(item).State = System.Data.EntityState.Modified;
  }
  context.SaveChanges();
  }
  }
  it is the class that was generated from EF Designer right? or maybe I’m misunderstanding on what this is suppose to accomplish. I taught it was suppose to be generic repositories where I have re-usuable code for any DB that I’m generating through the designer e.g. today I’m working with table1, and table 2 from DB 1 and I create a repositories for those using GenericDataRepository as the base class , now i want to build another repository with table 3, and table 4 from DB 2 for another application I wouldn’t have to rewrite the basic CRUD operations as they were implemented in the GenericDataRepository class which is the base class for the new repositories but I can’t see how GenericDataRepository can be a base class if the Entities class that it is referring to is the specific class that was created thru the EF designer for the DB and tables that you want to query.
  Yes, the Entities class was generated from the entity data model (EDM). The .edmx file that represents the EDM is an XML file that defines the conceptual model, the storage model, and the mapping between these. EF uses these mapping files to map entities and relationships in the conceptual model to the corresponding tables in the database.
  This means that whenever you want to make some changes to the model, e.g. include new tables, you have to update it. You can do this by right-click the .edmx file in the Model Browser window and select “Update Model from Database”.
  For more information about the mapping between objects and data and an overview of the EF, please refer to the following link:
  Thanks Magnus for the clarification.
  Hi Magnus,
  Great article and a really good help when trying to create my own solution so thank you very much!
  I would love to hear about how you’d handle users concurrently editing the same object and how to avoid conflicts. Marking an object as Modified makes EF write every attribute back to the database when ideally we only want the attributes that have changed. This would not only perform better, but would solve concurrency issues stopping one editing user overwriting another’s changes.
  Thanks again!
  Hi Magnus,
  Fantastic article! Got answers to a lot of questions I have had.
  Thanks!
  At step 9 you reference the IEntity interface, but don’t define that interface until your discussion on persisting disconnected graphs. Perhaps a forward reference…? Reading top-down, I started looking for this interface in the EF.
  Can you give some pointers on how to implement a lazy loading (or similar) scenario…? In my scenario, I have Clients with Plans with Accounts with Statements. Each statement has a binary column that stores a PDF associated with the statement and a list of transactions. I don’t want to bring down every PDF for every Statement if I query for a Client.
  For example, what if I just want a list of Clients for the top level of a TreeView and want to lazy load the sub nodes as they are expanded?
  Thoughts?
  Excellent blog, by the way. Thanks for that.
  Hi J,
  You have to be “connected” to be able to load anything, lazy or not. Since you are working in a disconnected environment here, the context that was used to fetch the client or account entities will no longer be around when the user of the client application expands the TreeView.
  You could choose to load all related entities upfront by using eager loading if you know that the client side will need them, or get the PDF files on demand by exposing a business layer method that returns the file contents based on some identifier of a transaction or statement. The latter alternative is probably the best option considering performance if you request a lot of entities with a lot of related binary files.
  Right… I commented too quickly. I had read through the article but hadn’t analyzed the code. Once I looked at it I saw that “eager loading” is explicit rather than automatic. That’s all I really need. Just so I can request a list of Clients without it automatically bringing down the entire hierarchy.
  Now, after I populate my TreeView root with Clients and someone expands a node to see that particular Client’s Plans, I figure I can “attach” all those Plans to the existing Client object simply by adding them to Client POCO’s Plans collection. That’ll give me a full graph that I can use for updates and makes navigation through the hierarchy on the client pretty easy.
  I have learned a good deal about EF and Generics from this post. It’s good stuff. Thanks, again.
  Magnus,
  What are you gaining with IBusinessLayer? Can you give me an example of where you’d have a use for that interface outside of the BusinessLayer class itself?
  Thanks.
  Interfaces let you separate the definition of objects from their implementation and make it easy to create loosely coupled software.
  In this case the implementation details of the business layer is hidden from the client and you can easily add another implementation of the business layer by simply creating another class that implements the IBusinessLayer interface.
  I understand the general benefit of an interface. I’m just curious why it’s applied here other than just to conform to a model. An interface makes sense where you might have several different classes that would want to implement it along with some additional class specific stuff (your repository comes to mind). I suppose that if you wanted to replace the BusinessLayer class the interface might be a means to verify that you’ve implemented all the functionality… Anyway, that might just be a philosophical debate.
  Here’s a real question… (keeping in mind that I am now refactoring to incorporate the structure in this blog to get passed some issues I was having with maintaining dbContexts, etc…)
  I was using static classes for the BL stuff so that there was no need to instantiate a BL object every time you wanted to access data. In your BL, it seems you also instantiate an instance of each repo every time you instantiate a BL. Is there any performance concern with that? What if I have 20 or more entity types. Would I see a benefit to a static BL that only has to instantiate each repo once?
  In my case, I have a multi-tenant scenario. The user logs in and the BL caches some info about the logged-in user so that it can filter all future requests to data specific to that tenant. I could use static members for that bit, I suppose.
  So, I guess my question is, why not make use of static classes? (For one they can’t implement interfaces, which is how I ended up at the original question on why you had used the interface.) But would a static class, in this case, be more efficient?
  Thoughts?
  Hi Magnus,
  Blog is really helpful to design architecture using EF. Thanks for sharing.
  I have one questions here.
  Why ‘IGenericDataRepository’ and ‘GenericDataRepository’ are derived from ‘IEntity’? It seems that there is functionality exteded from ‘IEntity’ interface.?
  Hi J,
  Answer to your question of ‘Why not to use static classes’ is use of static classes meanse there is direct dependancy (coupling) between objects of Business layer and UI / Client.
  As Magnus has designed BL using interfaces ensures that system is build over the principle of loose coupling (DI) and you could impliment it easily by any IOC containers availables. This patterns ensures easy testability and maintanability.
  Let me correct Magnus if above details are not on right track.
  Hi Ranjan,
  The generic IGenericDataRepository interface doesn’t derive from the IEntity interface but the type parameter T is constrained to derive from the IEntity interface:
  Hi Mangus,
  Look here: IList GetList(Func where, params Expression<Func>[] navigationProperties)
  I think there should be Expression<Func> where – in this case “where” will be translated to SQL
  Also related to GetSingle
  Mangus, It would be nice if you extend this repository with sorting and paging support. Thank you
  Hi Magnus,
  Sounds good.
  Thanks for quick updates.
  Hi Vitaliy,
  Yes, when using a Func<T, bool>> you are basically calling Enumerable.Where and the filtering is done in memory while using an Expression<Func<T bool>> will result in a call to the IQueryable.Where method.
  I answered a forum question regarding this a couple of months ago and should probably modify the Get methods in the sample code to use expressions:
  Magnus… In an attempt to make sure the user is getting the latest data, I added a refresh method to the repo/BL and call it before I display a details screen:
  public virtual void Refresh(params T[] items)
  {
  using (var context = new Entities())
  {
  DbSet dbSet = context.Set();
  foreach (T item in items)
  {
  dbSet.Add(item);
  foreach (DbEntityEntry entry in context.ChangeTracker.Entries())
  {
  IEntity entity = entry.Entity;
  entry.State = GetEntityState(entity.EntityState);
  }
  }
  context.ToObjectContext().Refresh(System.Data.Objects.RefreshMode.StoreWins, items);
  }
  }
  When I examine the code, it appears that all the data is actually getting refreshed. But, in the View, the bindings associated with the navigation properties break and no data (new or old) is displayed. How would you go about refreshing the data without breaking the bindings? (This appears to only be a problem if the data in the database has actually changed.)
  Hi,
  If i have a third entity Adress, with also a one to many relationship between Adress and Employee, how can I change the GetAll() call to get the departments, their employee, and each employee’s adress ?
  (Sorry for my english)
  Hi, great Post..
  I don’t know if I am doing something wrong, but when I create the IGenericDataRepository , I got the following error:
  ” The type or namespace name ‘IEntity’ could not be found (are you missing a using directive or an assembly reference?) ”
  Should I include some other reference or “using” ?!
  best regards !
  Hi Pedro,
  The IEntity interface is a custom interface that defines a state property to let the entity objects track their own state. See the “Persisting disconnected graphs” section for more information.
  Hi Magnus – Great post.
  I have a question about the eager loading, How to load deeper down.
  I.e. Departments have employees who have kids how would you load everything?
  repositotry.GetAll(e => e.Employees) would get all the departments with the employees, but how can you load in the kids as well from employee collection?
  Magnus,
  Do you have any advice on how to manage graphs on the client side? I keep running into an issue where the object state manager complains about duplicate keys. In my schema Plans have Accounts which are associated with a Custodian On the client, for instance, I’ll load an account. On demand, I will load the custodian that account is associated with and populate the entity’s nav prop. If I load another account and then need its custodian, I end up with two different references to the same custodian. The if I try to update the graph, I end up with the conflict. (I tried using context.Entry, rather than dbSet.Add, but it didn’t help. Do I have to create a repository manager on the client to make sure I only ever use the same instance of a particular entity?
  Thoughts?
  Thanks.
  J
  If i use WCF service to connect UI(WPF) to server side where BL,DAL etc exists. how can i implement CRUD operations…..????, i dont have referece to any layer from UI other than i added service to UI.
  for more info please check part2 and 3 of the following link
  plz help ..in crud over wcf…
  Nice article Magnus. Just wondering, would not the custom property definitions ( i.e. EntityState {get;set;} )be overwritten everytime the Poco entities are regenerated? How do you stop that from happening?
  Hi Magnus, great Article. I learn a lot from this. Thanks.
  Hi Tedd, I think POCO created partial class when generate entities. In this case, you can create the new partial entity class (with the same name) that contain other/additional properties such as EntityState {get; set;} or whatever. Is that correct Magnus?
  @erizaldi
  I did as you suggested – created partial classes to implement IEnity.
  One word to others – get the spelling right on your class name or you will be spending loads of time wondering why “there is no implicit reference conversion from ‘Department’ to ‘IEntity’ :=)
  @rbanning:
  Thanks man. I wound up tinkering with the T4 templates that EF uses to generate these entities so that on creation the entities inherit IEntity. Was worthwhile in the end.
  Hi
  this question is about DAL, imagine you separate POCO classes from your edmx in a Project. but now you need to “decorate” this classes for diferent needs like for example metadata for RIA services or validation for MVC4 project….
  how did you implement this without using partial classes, and having different projects for each need?
  Thanks