I am playing around with Entity Framework to see how it can be used in a new project I am working on. I put my edmx file in a class library so the Entities (and database access) can be used in multiple places. Currently I have a web project and a console project both referencing the class library.
One of my Entities has a Partial class defined with a static method. The purpose of the method is to accept some parameters and create one or more instances of the specific class. My first version of the method created an ObjectContext instance, created the Entity class (or classes), and returned the Entities to the calling method. The calling method then updated some properties and tried to save the Entities using a new ObjectContext instance. Obviously this did not work because the Entities were bound (correct term ??) to the Context created within the static method.
After some research, I modified the static method to also accept an ObjectContext reference to ensure that all the Entities where created and then later on manipulated and saved using the same Context. This works fine but the design just feels wrong.
Assuming that my one static method may grow into many more, or that my app (especially the web app) would probably benefit from additional layers (DAL or even a Service Layer), does it make sense for all these classes to require an ObjectContext parameter?
I have read on many postings that creating an ObjectContext via a Singleton pattern is a bad idea because "many clients would use the same object". My problem with that is I do not see how that is possible. In a local console app there is only a single user running the app. In a web app there would only be a single user on each request. Where is the user sharing problem? Not a single article/posting mentioned it...but where they referring to a Singleton pattern storing the object instance in the Application context?
I have also seen postings focused on web usage and storing the object instance in the users Session object via the HttpContext object. This makes sense but does not seem to address non-web usage.
I think that whatever solution is appropriate (static methodm, Factory object, etc.) would most likely be implemented in my class library so obviously it needs to support both web and non-web solutions. Maybe check for HttpContext to determine what environment it is running in.
I was hoping http://www.west-wind.com/weblog/posts/2008/Feb/05/Linq-to-SQL-DataContext-Lifetime-Management would be informative but I am having a hard time wrapping my head around the post and the example code seems like overkill for instantiating and sharing a simple object. (Although I am sure I am just not getting it...)
Any thoughts are appreciated.
Thanks.
The issue is not that “many clients would use the same object.” The issue is that the ObjectContext is intended to be a single unit of work. If you use it for many different units of work, you will find that there are a number of problems.
Memory usage will grow and grow.
Your application will become slower as object fixup has to do increasing amounts of work.
Multithreading won't work
The solution is to use the ObjectContext in the manner it is intended, namely, as a single unit of work.
Related
I've set up a very simple (Universal Windows) App in C++/WinRT.
It's just App <- MainPage <- DataViewModel <- Data for now.
MainPage has some Sliders etc. which are bound (x:Bind) to DataViewModel, which contains an instance of Data. Working fine so far.
However, the Data is a member of DataViewModel. This seems to be an obvious code smell. Data should not be "owned" by the GUI. All Examples/Samples I've come across seem to be set up like this, though.
I also want to run a background thread (pure C++ code) that works with one and the same instance of Data.
The question: Who "owns" Data. How do I connect things? How to pass the reference?
My best idea so far: The App class itself should just own the one instance of Data. The MainPage ctor should take a Data& and pass it on to the ctor of DataViewModel. However, I don't seem to be able to write a custom ctor for MainPage, because there's generated code involved.
Just pointing me to well coded Sample App would also be appreciated.
IInspectable (in the comment above) makes a noteworthy point: "Ownership really only matters when non-static lifetimes are involved. If Data represents data with static lifetime then there's nothing inherently wrong with exposing it through a static App class member."
In this vein, don't limit your thinking of Data (i.e., the model) to just object(s) which some other object owns. The model should be thought of as a wholly independent component.
Let me approach this notion from another angle. Most people will readily describe MVVM as three independent "layers" or "components" or what have you, wherein the model "doesn't care" about the view model, which in turn "doesn't care" about the view.** In code (as you have seen yourself), you're probably going to find some clear cut ownership patterns to reflect that basic premise. For example, if we're following the the "view-first" approach like the Microsoft samples, you'll start with your App object, which owns an instance of a view object, which in turn instantiates a view model instance.
But the key to MVVM is not who owns whom, it's the relationships between those layers. If you wanted to, you could write a program where, say, the views and view models were all static members of the App class and still have a (conceptually) textbook MVVM structure once everything is hooked up. From that perspective, it doesn't matter where ownership resides.
Now, the thing about Microsoft samples like the Photo Editor is that ultimately they're just demonstrations of how things can work, not a treatise on design patterns. Consider when your data is coming from a database or a web service. Where do you draw the conceptual line between model and view model? The question may sound pedantic, but the way you evaluate these things influences your design decisions.
Which brings me back to your specific question. If it seems like code smell to you when examples you find online stick the model data any old place, you're not wrong. In "real life," the model can be an entire API, not just one illustrative class. You'll potentially have an elaborate subsystem delivering data to you that depends on services completely separate from your application. Or it might be an opaque third-party API that you're calling into via global functions, etc. Just remember that the key isn't "ownership," it's (the conceptual) "relationship." ***
** As a side note, you mention Data being a member of DataViewModel and describe this as Data being "'owned' by the GUI." Ideally, the view model should have no inherent ties to the UI, just application logic. Don't think of it as an extension of UI functionality.
*** But please don't take this post to imply that the actual implementation of the MVVM paradigm isn't important. That's true of any design pattern. The exact form that implementation takes depends on the specific application and whatever your boss wants you to do. All I'm saying is, don't get hung up on ownership. :)
I need to retrieve a large graph of entities, manipulate it in the UI (adds, updates, deletes), then persist it all back to the database. After various SO questions and experiments, I'm finding this mass "detached graph update" approach to be very problematic, so I'm now rethinking my approach.
It's only a 2-tier WPF app, so I'm now thinking of having a long-running context that exists for the duration of the UI used to manipulate the entity graph - that way it can track changes automatically. However I'm not sure how to approach this architecturally.
The application currently has three projects - the UI, business tier, and one for the edmx & generated entities. My business tier has a CustomerManager class that exposes a method to retrieve a Customer graph (orders, order lines, etc.), and a method to persist the Customer graph. Assuming that the UI holds on to the same instance of the CustomerManager class, and therefore the same context, changes to the graph (adding and changing entities) will be tracked.
Deleting an entity is a bit more tricky, as the context must be used to do this, i.e.:-
context.Set<Order>().Remove(orderToDelete);
Looking for some architectural advice really. Do I just expose a DeleteOrder method in my CustomerManager class that does this? Given that I have a dozen other entity types, I would presumably need to expose similar methods to delete orders, products, etc.
Is it a sensible approach for the UI to hold on to the same CustomerManager instance, or is there a better way to manage a long-running context? A logical place for the DeleteOrder method would be in my Customer entity (partial) class, but as these classes are in a separate project from the business tier (which is where the context resides), I guess I can't do this (unless I pass the context to the DeleteOrder method)?
Your long living context idea will work only if your context lives in UI and UI talks to database directly to get and persist data. Involving WCF between your UI and context always result in serialization and it causes entity detaching = not tracking changes (unless you use STEs). Having long living context in WCF service is too problematic and in general bad practice.
Have you considered WCF Data Services? They provide client side tracking to some extend by using special client side context.
I have recently created a pretty robust API built around Entity Framework's DbContext. I am using a lot of metadata programming and taking advantage of the fact that I can get my data with a call like DbContext.Set(typeof(Customer)). Only, in my API I do not know at compile time what type I will be passing to the Set method. This is working very well with EntityFramework and I would like to add another layer abstraction and have it work with both EntityFramework or DataServiceContext. So, I really have two questions.
Firstly, and more specifically, is there a DataServiceContext (i.e. odata/wcf) equivalent to the DbContext.Set(type) method?
Secondly, and more generally, is there a good resource that compares the APIs provided by DbContext with DataServiceContext?
EntityFramework and DataServices client API should not be mixed. Even though they look similar they are not. DbSet represents entity set. I don't think there is a strong contract around entity sets in DataServiceContext. Instead the name of the entity set is passed to methods that need to know this (e.g. look at DataServiceContext.AddObject() or DataServiceContext.CreateQuery() methods) as strings. In some sense it makes it much easier to program the DataServiceContext dynamically. On the other hand you still need to know what is on the other side of the pipe (i.e. the server). As said above WCF Data Services and EntityFramework are different technologies (even though they can work together) and their APIs, though similar, serve different purposes. Therefore comparing them would be like comparing apples to oranges.
The DbContext API in the client side is not the same from DbContext on server side. The main goal is to expose the data and model, which can be done pretty well. I think you may be overengeneering your app, since WCF Data Services can provide enough funcionalities.
Here is a link from Ladislav Mrnka, who is very good at entity framework, he shows how you could expose your robust api with WCF Data Services.
Implement WCF Data Service using the Repository Pattern
I am developing a WPF desktop app that uses Entity Framework 4 and SQL Compact 4. I have seen two distinct styles of Repository classes:
The Repository instantiates an ObjectContext, which is disposed of when the Repository is garbage-collected. The lifetime of the ObjectContext is the same as the lifetime of the application.
A separate DataStoreManager class creates and holds an ObjectContext for the life of the application. When a repository is needed, a command gets an ObjectContext reference from the DataStoreManager and passes it to the constructor for the New Repository. The lifetime of the ObjectContext is the lifetime of the application.
Is either approach considered a bad practice? Does either present any absolute advantages over the other? Is either approach considered best practice? Is either more widely accepted or used by developers than the other? Thanks for your help.
I would have thought that holding an ObjectContext open over multiple accesses would be bad practice. As soon as it becomes corrupted then you would need to recycle in and handle the corruption.
The Repository pattern is more for abstraction of data access but doesn't necessarily map to lifetime of context.
The unit of work pattern is more about encapsulation of one or more database/repository accesses i.e. a use case may have you adding a new Blog and then adding the first default post, this may require calling two repositories, at this point you might want to share the context and encapsulate these two commands in a transaction. Adding a second post might be done hours later and be a new context/unit of work.
DJ is right in mentioning Context lifetimes which you'd set generally at an application level.
The best practice is depended on how your users are going to use the application:
And how your application is structured.
if there is only one user using your application at one time, you can even create your entity context as a static instance.
context can be used per request, per thread, per form.
read more: http://blogs.microsoft.co.il/blogs/gilf/archive/2010/02/07/entity-framework-context-lifetime-best-practices.aspx
Is it possible in Entity Framework CTP5 to construct retrieved persisted entities via an IOC container?
I'm using Ninject and it's tied in fine with MVC, but I need to inject some services into my domain objects when they are constructed for some business rules.
I'd rather do this using constructor injection than method or property injections.
I'm not sure what, exactly, you're trying to accomplish here, but EF has almost no extensbility points. The best you can do is hook into the ObjectMaterialized event fired by ObjectContext. In CTP5, you need to cast your DbContext like so in the constructor for your DbContext:
((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized +=
this.ObjectContext_OnObjectMaterialized;
And then implement your function ObjectContext_OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e). You will be able to access your object, which unfortunately has already been materialized. Depending on your needs, you might be able to hack in some interesting behavior here.
BTW, this sentence makes no sense to me:
I need to inject some repositories into my domain objects when they are constructed for some business rules.
Doesn't this go against Persistence Ignorant Domain Objects?
I tend to do the inverse of what you are trying to do. I make my domain objects as ignorant as possible (they are essentially property bags). When you need to perform some sort of action, like send an email, then I would use a service for that and have the method take in the domain object it needs to perform the action on. In this case, you would simply need to inject services into various parts of your application (which is much simpler to accomplish with Ninject).
I think EF code first CTP 5 can be of some help. It honours IValidatableObject interface, which takes ValidationContext object as an argument. The ValidationContext is a ServiceLocator so you should be able to get the instance of the IoC container using the validationContext object. (This is just my initial thought, I haven't tried anything though). Sorry, if my English is not very understandable.
Update
Sorry, just after I posted this comment I realized that the question is quite different than what I understood. So, I did try few things myself, and after some hit and trial and much more googling I was able to get somewhere. I was planning to post the answer here, but then thought against it, since the answer would be very long. So, I did post this blog instead.
http://nripendra-newa.blogspot.com/2011/02/entity-framework-ctp5-injecting-with.html
May be this might help some googlers searching for the same. Hope I got the question right this time.