Can I use EF code-first with SQL Server CE on WPF? - wpf

I would like to use a local SQL Server CE in my app; I've read that using EF code-first I can let the system create the db starting from POCO classes; I've configured EFCodeFirst.SqlServerCompact using NuGet but it's not clear to me how can I use it in my WPF app....can anyone help me?

It doesn't really matter whether you use the default WPF style application development or MVVM pattern, as long as you have a separate data layer.
Your data layer should hide away all of the DB implementation logic, including the creation of the DB from the rest of your code.
You could implement it using the Repository pattern, but as long as it provides a known interface and definitions for the data objects that your business logic requires you should be okay.
Note that the data objects used by the other layers of code do not need to be the same as the POCO objects used by the DB.
If you have your data layer accessed by a Singleton class that implements the layer's interface then you could automatically call the DB creation code if the DB can not be found when DataLayer.Instance (for example) is called.
The important thing to remember is that only the internal workings of the datalayer should know where the data comes from the rest of your code should be DB agnostic, only caring that it has the data that it needs, not where it comes from.
As for practicalities here's a link that gives a Code First with EF example.

Related

umbraco 7 how to access database MVC

I have Umbraco 7 website with MVC.
I want to perform some custom action on the database.
As I understand I should be using DbContext to connect.
I have referenced System.Data.Entity to get to DbContext class. However when I'm trying to use DbContext I'm getting an error saying
The type or namespace name 'DbContext' could not be found (are you missing
a using directive or an assembly reference?)
In my models namespace:
public class umbracoDbDSN : DbContext
{
//some code
}
Can you let me know what I am missing?
Thanks
You are mixing things up. Umbraco uses PetaPoco as ORM, not entity framework. You don't need to include the System.Data.Entity. Neither you need the DbContext.
However, if you have existing DataLayer logic which you need to incorporate, for legacy systems, you might need to continue with your code above. Then look for entity framework tutorials on the internet to continue your journey.
If you are not dragging legacy stuff, then the question is: do you want to perform queries on custom tables or do you want to query the Umbraco tables for some reason.
Let's start with the last one. Querying the umbraco tables:
If you want to connect to the umbraco SQL tables, I start wondering why. There is a ContentCache, which is blasting fast, and it enables you to query very quickly everything you need from the content section. You have API's for relationships, media, users, members and everything you need. So the question remains, WHY would you ever connect to the umbraco tables.
However, if you want to store data in custom tables, I would read this article of Warren: http://creativewebspecialist.co.uk/2013/07/16/umbraco-petapoco-to-store-blog-comments/
The idea is simple, you reuse the existing code base to extend umbraco behaviour without storing stuff in the content section.
Below a simple example for reusing the databaseconnection while querying some proper created table...
var db = ApplicationContext.Current.DatabaseContext.Database;
// Fetch a collection of contacts from the db.
var listOfContacs = db.Fetch<Contact>(new Sql().Select("*").From("myContactsTable"));

Where the data was put in wpf client app with client/server model with mvvm light?

There is a class which is responsible for communicating with server and hold the most of data. In client, There is without database.
VMs will get required data from the class instance.
Now I'm doubt where the class instance to be put, in App class? in ViewModelLocator class? or others?
Are there some opensource projects like this?
This really depends on the size of your project. If I write a small MVVM application (with a single project), then I create the following folders:
Converters (if required)
DataTypes - some developers put this into 'Models' also, but I prefer to separate them
Models - I use this for data access classes <<< put your class in here <<<
Utilities - some developers call this 'Services'
ViewModels
Views
If the application is large, then I create separate projects with these names instead and add a few others as well.

Where/how should the database code go in a class/application?

So, I don't know if the question is explicit enough, but here's my problem:
I am writing a small application in VB.Net, that retrieves information from a website and present it to the user. Basically, I have written a class, which has a Get(URL) method which retrieves the webpage, reads it and populates the various Properties (Read-only) of the object.
This class works OK.
Now, I would like to store that information in a Database (I'm using Access for now), so that I can read the data from the DB, if the class gets called for a known URL. As I'm fairly new to OOP and completely new to DB usage in desktop applications (no problems in designing the DB though), I am not sure on how to proceed:
Should I put the database code in my existing class?
Should I create an extended class based on the existing one, adding the DB code?
Should I create a completely different class for the DB data and put the switch logic (read from DB or from web) in my application?
...
I realize that my question may sound silly to the most experienced of you, but I'm new to this and I would really like to learn how to do things the right way the first time!!!
Thanks!
This is what I would do:
Create a new class for the database code, and create an
interface for it that it implements.
Then create another class that has the code to fetch the web data. Make it implement the same interface.
Now you can subsitute either class to do your data access from your controller class.
Also, I usually put database and data access in separate projects from my service and ui classes, which are in their own classes, but that might be overkill for your situation.
If you'd like to read more on the subject, look up n-tier application design. The tier you're talking about here is data access.
http://en.wikipedia.org/wiki/Data_access_layer

Prism 4 WPF App - Solution Architecture with MVVM, Repositories and Unit of Work patterns implemented

I'm new to .Net and trying to learn things. I'm trying to develop a Prism4 WPF app with
Visual Studio CSharp 2010 Express Edition,
Prism v4,
Unity as IoC,
SQL Server CE as data store.
I've studied a lot(?) and infuenced by this and this among others, and decided to implement MVVM, Repository and UnitofWork patterns. This application will be a Desktop application with a single user (me:-)
So, I've created a solution with the following projects:
Shell (Application Layout and startup logic)
Common (Application Infrastructure and Workflow Logic)
BusinessModuleA (Views and ViewModels)
BusinessModuleA.Model (Business Entities - POCO)
BusinessModuleA.Data (Repositories, Data Access (EF?) )
BusinessModuleB (Views and ViewModels)
BusinessModuleB.Model (Business Entities - POCO)
BusinessModuleB.Data (Repositories, Data Access (EF?) )
My questions are:
Which projects should reference which projects ?
If I implement Repositories in 'BusinessModuleX.Data', which is
obvious, where should I define IRepositories ?
Where should I define IUnitOfWork and where should I implement UnitOfWork ?
Is it ok if I consume UnitOfWork and Repositories in my ViewModels ?
Instict says it is bad design.
If (4) above is bad, then ViewModel should get data via a Service
Layer (another project ?). Then, how can we track changes to the
entities so as to call the relevant CRUD methods on those objects at the Service Layer?
Is any of this making any sense or am I missing the big picture ?
Ok, may be I've not made myself clear on what I wanted exactly in my first post. There are not many answers coming up. I'm still looking for answers because while what #Rachel suggested may be effective for the immediate requirements, I want to be careful not to paint myself into a corner. I've an Access Db that I developed for my personal use at Office, and which became kind of a success and now being used by 50+ users and growing. Maintaining and modifying the access code base has been fairly simple at the beginning, but as the app evolved, began to fall apart. That's why I have chosen to re-write everything in .Net/Wpf/Prism and want to make sure that I get the basic design right.
Please discuss.
Meanwhile, I came up with this...
First off, I would simplify your project list a bit to just Shell, Common, ModuleA, and ModuleB. Inside each Project I'd have sub-folders to specify where everything is. For example, ModuleA might be separated into folders for Views, ViewModels, and Models
I would put all interfaces and global shared objects such as IUnitOfWork in your Common project, since it will be used by all modules.
How you implement IUnitOfWork and your Repositories probably depends on what your Modules are.
If your entire application links to one database, or shares database objects, then I would probably create two more projects for the DataAccessLayer. One would contain public interfaces/classes that can be used by your modules, and the other would contain the actual implementation of the Data Access Layer, such as Entity Framework.
If each Module has it's own database, or its own set of objects in the database (ie. Customer objects don't exist unless you have the Customer Module installed), then I would implement IUnitOfWork in the modules and have them handle their own data access. I would probably still have some generic interfaces in the Common library for the modules to build from though.
Ideally, all your modules and your Shell can access the Common library. Modules should not access each other unless they build on them. For example, a Customer Statistics module that builds on the base Customer module should access the Customer module.
As for if your ViewModels should consume a UnitOfWork orRepository, I would have them use a Repository only. Ideally your Repository should be like a black box - ViewModels can Get/Save data using the Repository, but should have no idea how it's implemented. Repositories can get the data from a service, entity framework, direct data access, or wherever, and the ViewModel won't care.
I'm no expert on design architecture, however that's how I'd build it :)
I would highly recommend you to get the Introduction to PRISM and Repository pattern inside Design Patterns Library training videos. They are great ones. Hope it helps

How to implement DI using DbContext in Windows Form

I have a class running in a winforms app which uses EF Code First. The DbContext is created via DI through the class constructor. All works well.
The problem is the data being referenced is also being modified via a web site, using the same DI pattern with EF Code First, and the data changes are not being reflected in the context instance in the winforms app.
I can solve this by recreating the DbContext object in winforms every time I access it, but seems to be more of a service location pattern to me?
Is there a true DI technique to achieve this?
Or should I remove the context from the DI and use service location?
Were you not happy with the answer to your other question (http://stackoverflow.com/questions/7657643/how-to-force-ef-code-first-to-query-the-database) which suggested using Detach, AsNoTracking or Overwrite Changes?
1) Maybe you could pass an interface that has the ability to create a DbContext, instead of the context itself.
using(var context = _contextFactory.Create()) {
var entity = from table in context.Blah...;
}
The Create method could either create the concrete class itself (defeating the DI pattern a bit), or use service location to have one created for it. Not that nice, but it's better than embedding service location calls everywhere and still means you're controlling the lifecycle yourself.
2) Change the WinForm to read from a webservice run by the website, effectively similar to disabling caching.
3) Deep in the heart of MVC (well not really that deep) it is referencing the DI container directly and using it as a service locator to pass as arguments for newly created objects. Technically you could do something similar in WinForms, but it would need you to split your application up into little chunks (controllers) that don't have a very long lifetime. Maybe it's worth looking at some MVC/MVP frameworks for WinForms, although I found myself cringing at most I saw after a quick google.
The problem is the data being referenced is also being modified via a web site, using the same DI pattern with EF Code First, and the data changes are not being reflected in the context instance in the winforms app.
This is a problem with your expectations.
If your web service and window forms app are in separate processes, they won't share in-memory data.
If you want to sync their in-memory data, simply re-query in one context after committing to the database in the other. This is the same as trying to share data between different SQL connections.
I can solve this by recreating the DbContext object in winforms every time I access it, but seems to be more of a service location pattern to me?
If you want to recreate the DbContext repeatedly, you could use an abstract factory to allow manual re-creation of the object, yet allow you to inject the specific implementation into the factory.
This is not (necessarily) the Service Locator pattern, and you would have to ensure that you manually dispose your DbContext instances. I'd give you some example code, but different DI containers have totally different ways of accomplishing a factory pattern.
Or you could simply make sure that you commit your data on the web service side, and re-query the data on the WinForms app side.

Resources