Custom ValidationContext for EF? - entity-framework-5

I'm using EF as my dataprovider to save and validate my items.
I have some custom validation logic which needs access to other services or items.
I know the ValidationContext class supplies these options.
My question is how can I get my own validation context with an service provider or item to EF?
When I implement the IValidateObject interface on my POCO entity I get an instance of the validation context, but where can I make sure my own ValidationContext is used instead of the EF default one?
I want to base some validation on the fact that a service or item is available in the ValidationContext

To pass the ValidationContext you need to override DbContext.ValidateEntity(). The method takes two parameters - entity entry and items. You would pass your validation context in the items dictionary. Take a look at this stackoverflow question.

Related

How to share business logic between DTO & domain model?

I'm trying to refactor a codebase that was passing domain models to the views, to use DTOs instead.
Overall everything looks cleaner now, except one point: I have some business logic that belongs to the domain but needs to be executed in the view as well.
Example: I have an Activity class, that has a method to check whether a given User can edit it:
class Activity {
public function isEditableBy(User $user): bool {
...
}
}
The domain service layer uses this method to ensure that the Activity can be edited, and throw an exception if not.
The view uses this method to display an Edit button if the Activity is editable by the user.
Question: How to avoid duplicating this logic in the DTO and the model?
I thing you should not put logic in the DTO at all due to its definition "Data Transfer Object". So, "data" not "logic". Instead you can calculate result of the isEditableBy() method in your application service layer, put this result into a DTO and use the DTO in the view layer.

Automapper to update an existing object as opposed to creating a new one [duplicate]

This question already has answers here:
Automapper: Update property values without creating a new object
(4 answers)
Closed 4 years ago.
Is there any way to use Automapper 5.1.1 to update an existing object as opposed to creating a new one.
For example we have a Customer entity and a CustomerViewModel. We would like to update an existing Customer with the CustomerViewModel field values.
Would greatly appreciate your assistance.
It is not adviced to use Automapper to map a model to your Entity. Dependencies or Informations can be overwritten if it isn't used wisely.
But to use it as you want, you only need to create a map from your Model to your Entity and then call
Mapper.Map(myModel, myEntity);
The mapping to entity Problem
I guess you use a ORM like NHibernate or EF, then your Entites are Proxies, where references are proxies too and so on. Now lets imagine you have an ASP.NET MVC Project and you map your Entity to your ViewModel. You show your Model in your View as a form, but you only show the properties that you need in your view, not all that are set in your ViewModel. Then the user sends the Form back to you and your Controller gets the ViewModel back, but this time not all Properties are set, because your View only knew the ones that were shown. If you map your ViewModel back to your entity, all unitialized properties are in there default state and will overwrite the valid data f rom your entity.
Another Problem is, that AutoMapper uses Reflections to set the Properties. Normally the right to exist for an ORM is the possibility to easy implement an DomainLayer. The DomainLayer has some Validations, Calculation... on the Entity itself. If now the Properties set with Reflection it would ignore the Business logic and no Validation, Calculations.... would be executed.
So my advice is, Don't map to Entities ;)

spring integration: Custom header enricher that records header values to database

I would like to have a custom header-enricher that takes the header values to be added and adds them to the header and also, records them in the database. I was trying to create a custom spring tag say: db-recording-header-enricher and use that instead of header-enricher tag wherever I am interested in recording the headers to the database.
And here's what I have so far:
I have custom spring XML name-space with custom element db-recorder-header-enricher correctly configured. I have a test spring integration xml that I am using to test whether the parser is functioning correctly. The test is loading the test XML correctly, except I want to use my custom parser below instead of the HeaderEnricher which it picks up by default as the transformer.
The processor for db-recording-header-enricher looks like:
DbRecorderHeaderEnricherParser implements BeanDefinitionParser {
#Override
public BeanDefinition parse(Element element, ParserContext parserContext) {
BeanDefinition beanDefinition = new StandardHeaderEnricherParser().parse(element, parserContext);
// Set the header Enricher processor to be my custom processor
// beanDefinition.setHeaderEnricherProcessor(dbRecordingHeaderEnricher);
return beanDefinition;
}
}
The problem I am facing is this:
Based on the parser definition above if I use StandardHeaderEnricherParser to parse my xml, I cannot find a way to associate DbRecordingHeaderEnricher as the transformer for the parsing of the header-enricher. Even if I extend StandardHeaderEnricherParser the method below is final, so again I cannot seem to give it my custom parser for transforming purposes.
#Override
protected final String getTransformerClassName() {
return HeaderEnricher.class.getName();
}
All I want to do in my custom parser is associate my custom header enricher (which extends HeaderEnricher class) for the parsing of the headers and creating records into the database for the headers added. If it's not possible the way I am thinking about it, what are some of the other alternatives? Can I use AOP/advice on a transformer?
This is fairly advanced. You will need a schema, a namespace handler that associates the parser with the namespace element and the parser itself.
It might be simpler to use a <transformer/> and simply reference your bean that adds the headers (and stores them).
If you want to learn how to write your own namespace; a good place to get started is the STS project templates which will create all of the boiler plate for you.
EDIT:
In response to your updates...
Since it's still a bean definition, and not yet a bean, you can simply change the beanClassName property...
BeanDefinition beanDefinition = new StandardHeaderEnricherParser().parse(element, parserContext);
beanDefinition.setBeanClassName(Foo.class.getName());

Azure TableStorage HowTo?

I want to store Contacts on to Azure table(name and gender as a property). so I basically two classes . the one which derives from the TableSerivceContext and the other from TableServiceEntity. now I cant connect the pieces. What I will really do at the cotroller(I use MVC3)
tnx for any hint?
im assuming that you are receiving the properties (name and gender) via post from a view.
so your controller might be like this
public ActionResult DoSomething(User model)
{
}
so what you need to do is.. that. make a new ofject of the class thats derived from the TableServiceEntity. and assign the Properties.
like this
var tableUser = new TableUser(){Name = model.Name, Gender=model.Gender}
then from the class derived from TableServiceContext make an object. and use AddObject() method to add the user to the table
http://msdn.microsoft.com/en-us/library/system.data.services.client.dataservicecontext.addobject.aspx
This is what I have done recently to create a very simple MVC3 + Windows Azure Table sample application:
Created a Model Class DataEntity inherit from TableServiceEntity which include all the table properties needed to store along with PartitionKey and RowKey
Created another Model class DataContext inherit from TableServiceConext which includes IQueryable sets up the Table
Created a Controller class which creates HTTPGet and HTTPPost method type ViewResult returning View. The controller also have code to create the Table first using Model DataContext type and then added code to call AddObject as DataEntity type as below:
DataContext context = new DataContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
context.AddObject("DataEntryTable", dataEntity);
context.SaveChanges();
Finally you can create views from the controllers.
You would need to inherit ‘Contact’ from TableServiceEntity and a context class from TableServiceContext to provide all the methods to manage your ‘Contact’ entities. You can then invoke methods on the ‘Context’ class from anywhere (including the controller).
I have written an alternate Azure table storage client, Lucifure Stash, which does away with having to inherit from any base calls and supports additional abstractions over azure table storage. Lucifure Stash supports large data columns > 64K, arrays & lists, enumerations, composite keys, out of the box serialization, user defined morphing, public and private properties and fields and more.
It is available free for personal use at http://www.lucifure.com or via NuGet.com.
Download the Windows Azure Platform Training Kit and do the lab on Windows Azure Storage. In 15 minutes you will have a working prototype.

How can I combine/split properties with AutoMapper?

we're using Automapper (http://automapper.codeplex.com/) to map between entities and dto's. We have a situation where one property on an entity corresponds to three different properties on the dto, and we need to write some custom logic to do the mapping. Anyone know how we can do that? (We need to map both ways, from entity and from dto).
I notice that AutoMapper supports custom resolvers to do custom mapping logic, but as far as I can tell from the documentation, they only allow you to map a single property to another single property.
Thx
You can create a custom type converter. It allows you to define a converter for an entire type, not just a single property.

Resources