get Generic CRUD operation in EF - wcf

Is there any way or design pattern can I use to get Generic CRUD operations?
Because I’m working on n-tire application using EF in the data layer and I don’t want to use CRUD Functions in Every Entities.
Your help would be appreciated

You can use the Repository pattern, where you implement the repository as an interface and then a base class. For instance:
IRepository where T : class
void Save(T entity )
T FindById( T id )
....
EntityFrameworkRepositoryBase : IRepository
void Save( T entity )
{
// do EF specfic stuff
}....
Then for a given entity you can create(or inject) a concrete repository:
PersonRepository : EntityFrameworkRepositoryBase
From there, simply call the PersonRepository to Save or Find Persons.

Related

AspNet Core WebApi OData - Many to Many join tables

As is the recommended pattern in EF Core these days when you have a many to many join we do something like this:
Fluent API, many-to-many in Entity Framework Core
Having done that I'm faced with the issue as to how I go about exposing that in the OData model.
Since technically the Entity type definition has no key property (as it uses a composite key the OData framework doesn't like me adding the set to the model.
Whats the recommended approach to this problem?
It seems that EF and OData have become somewhat synced up, what would be even better would be if they could literally share model building code.
To that end I found that in the OData model build after calling AddSet I was able to define the key in the same way as I did in EF ...
Builder.EntityType<UserRole>().HasKey(ac => new { ac.UserId, ac.RoleId });
This is somewhat clean, I have not yet tried posting or directly requesting such a type yet, but expanding from either side of the relationship chain seems to work fine.
EDIT: Moredetails on the definition of this in controller ...
The Url needs to contain both key parts ...
HTTP GET ~/UserRole(123, 456)
the same with PUTs and DELETEs but POST's don't contain the key they are part of the object in the body.
The method signature must contain both key parts, here's some examples ...
public IActionResult Get([FromODataUri]int keyUserId, [FromODataUri]Guid keyRoleId)
{
...
}
public IActionResult Put([FromODataUri]int keyUserId, [FromODataUri]Guid keyRoleId)
{
...
}
public IActionResult Post(UserRole entity)
{
...
}

Id Encryption in spring-hateoas or Spring Rest Data

I have a question about a standard pattern or mechanism in spring-hateoas or Spring Rest Data about encrypting the IDs of the Resources/Entities.
The reason I am asking, a requirement to our project is that we don't deliver the id's of our objects to the outside world and they should not be used in GET Requests as Parameters.
I know, Spring Rest Data and spring-hateoas does not give the ids of the objects unless they are configured so but even that case I can see the ids in links.
I know I can use PropertyEditors or Converters to encrypt/decrypt ids before and after Json serialisation/deseritalisation but I just like to know is there a more standard way?
Thx for answers...
If you have the unique 'business id' property of your resource you can configure SDR to use it instead of the entity ID.
First you have to create lookup method of your entity with this unique property:
public interface MyEntityRepo extends JpaRepository<MyEntity, Long> {
#RestResource(exported = false)
Optional<CatalogResource> findByMyUniqueProperty(String myUniqueProperty);
}
Then use it to configure SDR:
#Component
public class DataRestConfig extends RepositoryRestConfigurerAdapter {
#Override
public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
config.withCustomEntityLookup()
.forRepository(MyEntityRepo.class, MyEntity::getMyUniqueProperty, MyEntityRepo::findByMyUniqueProperty);
super.configureRepositoryRestConfiguration(config);
}
}
After this customization you will have resource URI like this:
http://localhost:8080/myEntities/myUniquePropertyValue1

How to subclass Hibernate entity class effectively replacing the parent?

Given the following scenario:
A project using a framework
The framework defines basic entity classes (used for logging, user management etc.)
The project has application specific entity classes.
I want to subclass a framework class in a way that does not need changes to the framework code nor the framework specific database schema (apart from any constraints that maybe introduced by additional mappings).
Here is a simplified framework class:
package com.example.parent;
#Entity
#Table("entities")
public class ExampleEntity {
#Id
#GeneratedValue
protected Integer id;
protected String name;
}
And the application specific extension:
package com.example.child;
#Entity
public class ExampleEntity extends com.example.parent.ExampleEntity {
#OneToMany
#JoinColumn
protected Set<OtherEntity> otherEntities;
}
As you can see this just adds an additional mapping to an application specific entity class.
This won't work with Hibernate 4.3.11 out-of-the-box. It will try to create a discriminator column (dtype) which is not desired and IMHO not required here.
I want this to be as transparent as possible (i.e. without changing anything on the framework side) and without any additional manual mapping/casting in the application. Effectively, I want to trick Hibernate into loading only instances of com.example.child.ExampleEntity without the framework even noticing.
TL;DR
How to trick Hibernate into loading entities from the entities table as instances of com.example.child.ExampleEntity?
You can used #Inheritance(strategy = InheritanceType.JOINED) on the parent class. You can find an example here.
So it would work with
package com.example.parent;
#Entity
#Table("entities")
#Inheritance(strategy = InheritanceType.JOINED)
public class ExampleEntity {
#Id
#GeneratedValue
protected Integer id;
protected String name;
}
So you can join any other table to children or parent
This is the official documentation about inheritance mapping.

How to get Doctrine2 entity identifier without knowing its name

I am attempting to create an abstracted getId method on my base Entity class in Symfony2 using Doctrine2 for a database where primary keys are named inconsistently across tables.
When inspecting entity objects I see there is a private '_identifier' property that contains the information I am trying to retrieve but I am not sure how to properly access it.
I'm assuming there is some simple Doctrine magic similar to:
public function getId()
{
return $this->getIdentifier();
}
But I haven't managed to find it on the intertubes anywhere.
You can access this information via EntityManager#getClassMetadata(). An example would look like this:
// $em instanceof EntityManager
$meta = $em->getClassMetadata(get_class($entity));
$identifier = $meta->getSingleIdentifierFieldName();
If your entity has a composite primary key, you'll need to use $meta->getIdentifierFieldNames() instead. Of course, using this method, you'll need access to an instance of EntityManager, so this code is usually placed in a custom repository rather than in the entity itself.
Hope that helps.

NHibernate DTO Parent child relation

I have som entities and now want to make some DTO´s based on there entities using nhibernate.
I have a Service - Allocation -Ressource where allocation describes how the ressource is allocated for the service.
I want a DTO like
ServiceDTO
-Name
-RessourceDTO
where RessourceDTO also has a name.
In the examples I have see for NHibernate projection/DTO you either use properties or constructor. If I use The Constructor approach I would have something like
ServiceDTO(Name, List
But I can't figure out how to make this work.
Another approach is to extract all the services and then loop through them and hit the database each time, or extract a larger result and then make the DTO's
What is the best approach? I going to hide all of this inside a repository.
How about
public ServiceDTO GetDTOFor(int Id);
{
var service = Session.CreateCriteria<Service>()
.Add(Restrictions.Eq("Id", id)
.SetFetchMode("Resources", fetchmode.eager) // eager load resources
.uniqueResult<Service>();
return new ServiceDTO(service.Name, service.Resources.ToList()) // Copy the Resources
}