how to use DataAnnotations in desktop application - entity-framework

When we are using EF (f.e.) via MVC, we can use ModelState.IsValid to detect a model can pass DataAnnotations metadata or not. But how can I use DataAnnotations metadata in a desktop (win-forms / wpf) application?
More:
In fact, I want to create an object same as ModelState (a dictionary that can save properties and messages associated with each). Then, wrap the DAL by a validation-layer, in VL use metadata to validate models, that the VL can be used in any project. I know I should use reflector, but I haven't any experience. Thanks to any help and suggestion.

If you are using EF 4.1/4.1 dbcontext, it has a built in validation API that can check Data Annotation rules as well as IValidatableObject.Validate. I'm not quite sure that I understand your goal, but if it is to have the validation in the data layer then you can just use what's built in. (Here's an overview http://msdn.microsoft.com/en-us/data/gg193959).
If you want your own validator that is separate from the data layer, then look at the System.ComponentModel.DataAnnotations namespace for methods and other logic you can leverage to do your own validation.

Related

Is it better to use POCO objects or detached EntityFramework object to expose database via WCF?

I created a WCF service in charge of exposing my database's data since I don't want the database to be directly accessed by my application (for security reasons) and i need to be able to share data with third-party applications.
My solution is structured this way: WPF application -> WCFService library -> DataAccessLayer library. (Arrows define assembly dependencies 'depends on')
To implement the WCF service I considered to simply return detached EntityFramework objects from the service BUT it forces the main application to have a dependency on the DataAccessLayer library.
The only way i can get around that is generating POCO objects and use them to send them over the wire, but now i have to map values back and forth EntityFramework.
At the moment i'm generating POCOs dynamically via a T4 template and I'm using AutoMapper to map values back and forth EntityFramework.
The Wcf service will just have to implement the repository pattern to expose data.
Is this a good solution? Are there any other option?
Is there any shortcoming i should be aware of?
Depending on your constraints, I would have to agree with this solution.
I created an almost identical solution, although our motivations were slightly different. Our client was Delphi Win32, and at the time didn't have good support for JSON, so we had to use SOAP.
The client also didn't support nullable primitives, so the POCOs removed all unsupported types, and performed other changes to ensure interoperability, then we used Automapper custom mappings to handle the two way conversions.
All the WCF services (contracts and implementations) where also generated by T4 templates, using a generic repository. With T4 templates, I was able to generate a separate WCF service per table for CRUD operations, and then manually created WCF services that were business specific.
Finally, I was also able to used T4 templates to generate the Delphi repositories that interacted with the SOAP services.
Or
You could just as easily move the POCOs (and code generation) to a separate project, change your DataAccessLayer library to reference the POCOs library and only contain the Db context made up of DbSets of your POCOs, and Data access logic but no entities (which are now POCOs). Your clients will not need to have a dependency on the DataAccessLayer library.
So... a good solution, depending on your constraints.

Suitable design pattern for business to persistence layers

I am using mongoDB that stores a simple product collection. I'm accessing this database from mongolab's API, so there is no direct access to the actual DB.
On the the other side, I have a Product model that has the same properties as the product document in the DB.
My question is: what design pattern(s) is(are) suitable in order to connect my business layer to the persistence layer.
So far I see these steps:
Product creation:
Create and populate the Product Model
Construct the endpoint URL for the API
Send request
Product retrieval:
Call methods like getProductByName() or getProductByCode()
Construct the endpoint URL for the API
Send request
Create and populate the Product Model based on the response.
I want to make the persistence layer as abstract as possible because in the future I might change the way I store and retrieve data. Also, this will be a simple application, so there is no need in using complicated logic or full ORMs.
Well I'm not an Android developer but I think my answer might be helpful. If your persistence layer is really simple and you are just going to have several methods there, there's no reason to complicate it with overdesign. Here's what I would do if I were you:
Add a new project to the solution for DAL layer.
Create a contract/interface with all methods you need.
Add all DTO's you might need to serve as input or output parameters for the methods.
Create a repository class which implements the interface. make sure it deals with all the API stuff (constructing the endpoint, etc.)
Reference the newly created library in your business layer. Make sure you use IoC to instantiate it. It's important you always reference the interface not the class itself.
Add some mapping logic between your business layer stuff and persistence layer DTO's
Now if you want to store your data in a database directly or whatever, you will need to create one more class which implements the interface and replace the old one. The rest of your code will remain untouched. Btw, it will be easy to mock the persistence layer for unit tests then.
Hope it helps.

Entity framework and Business Layer / logic

im doing some self-study on architecture of a MVVM-light - EF Application
im trying to build a product/Receipt like app.
I have a Db/EF with a Product and Receipt Table/Entity in a many to many relation.
then i have a DAL wich simply uses Linq to do simple CRUD.
the question is where and how to put my business logic in this app.
a couple of ideas came to mind
option 1
-make a ReceiptBo (Receipt business object)
wich inherit the Entity Receipt class and Icollection(ProductBo)
the ReceiptBo class would be responsible for adding Product,calculating total and subtotal and calling the Dal for inserting.
maby this option seemed a little overkill.
option 2
-put the calculating methods in the generated Entity objects by using partial classes
and simply using the BuisnessLayer to call the Dal.
this would make the Buisnesslayer Classes obsolete in my opinion and im not sure that Entity classes should be used for Business logic at all ?
option 3
-make the Business Classes but dont bother using inheritance, just add products to the Entity's and do the calculations there and call the Dal for insert.
wich seems simple but not very elegant.
option 4
-none of the above and im clueless
right now im not using WCF but the idea is that i want to make this app loosly coupled so that it would be easy to implement it and further extend it.
also im a little confused about what an Business layer is. in some examples it is more used like a Dal that also does the computing, then others say this is not done.
some help would be great. thx
ps: sorry for my bad english
Really, I would go simple here and choose a common multi-tier architecture designed as follows:
a data access layer (basically, your Entity Framework model along with all your entities)
a business layer that exposes methods to access to your entities (CRUD methods + any custom method that run some logic)
a service layer that exposes stateless methods through WCF (service+data contract)
the presentation layer (in your case using MVVM pattern)
Views (XAML pages)
ViewModels (C# classes)
Model is represented here by the entities that are exposed through WCF by the service layer
I wouldn't add any method directly in the entities. All methods are defined in the business layer, and exposed by the service layer.
Usually I keep my business logic in my ViewModels, not my Models, and I view EF objects as Models. At most, they'll have some basic data validation, such as verifying length or required fields.
For example, an EditRecieptViewModel would validate business rules such as verifying values are in a specific range, or verifying that users have access to edit the object, or performing some custom calculations when a value changes.
Also, don't forget that ViewModels should reflect the View, not a Model, so not every Model will have a ViewModel of its own

MVC3 and EF Data first: what are the best practices?

It seems that most of the focus with MVC3 and EF4.1 is around "code first" - I can't seem to find any examples or tutorials that meet the following criteria:
uses an existing SQLServer database
has separate projects for web & data access (we will have multiple web apps sharing the same data access classes)
recommendations for validation
Does such an example or tutorial exist? Are there any documented "best practices" for how to accomplish this, or rationale for NOT having a solution structured this way?
It is quite common scenario and it depends if you want to use EDMX file for mapping or if you want to have mapping defined in code (like code first).
Both scenarios can be done as database first
You will create EDMX from existing database with build in EF tools in Visual Studio and you will use DbContext T4 generator template to get POCO classes and DbContext derived class
You will download EF Power Tools CTP and you will use its reverse engineering feature to generate code mapping, POCO classes and context for you
Neither of these approaches will add Data annotations. Data annotations on entities should not be used for client validation (that is bad practice) unless you are doing very simple applications. Usually your views have some more advanced expectations and validation in view can be different then on entity. For example insert view and update view can need different validations and it is not possible to perform it with single set of data annotation on the entity. Because of that you should move data annotations for validation to specialized view models and transform your entities to view models and vice versa (you can use AutoMapper to simplify this).
Anyway it is possible to add data annotations to generated classes via buddy classes but as mentioned it is not a good practice.

Extending Entity Framework

I'm developing a program which allows users to input some information which then gets stored and dynamically creates an image based on it.
I was going to use the Entity Framework to do the work with the data, but then I obviously need a way to generate the image. My thinking was that the "correct" way to do this was to somehow extend the data entity to include a function call like "CreateImage", or alternatively, to create a separate class not in the EF called "DataImage" which would have a "generate" method.
Extending the EF seems the "pure" way to do this, but I'm not sure how or if it's more practical than using the separate class.
Any thoughts on the best way to do this and how to do it using EF?
Putting this functionality in the EF would be a major violation of SRP. Breaking SRP has cascading negative effects as your application grows.
The approach you most likely want to take instead is a totally separate, encapsulated image generation service which takes interfaces that your EF entities implement. This decouples your image service from your data access completely; you get complete testability and zero dependencies right away.