Entity Framework 4.1 Dynamically retrieve mapped column name - entity

I am trying to construct an SQL statement dynamically.
My context is created dynamically, using reflection finding classes deriving from EntityTypeConfiguration and adding them to DbModelBuilder.Configuration.
My EntityTypeConfiguration classes specify HasColumnName to map the Entity property name to db table column name, which I need to construct my SQL statement.
namespace MyDomain {
public class TestEntityConfig : EntityTypeConfiguration<TestEntity>{
Property("Name").HasColumnName("dbName");
}
}
From What I have researched, it seems I can get access to this information through MetadataWorkspace, which I can get to through ObjectContext.
I have managed to retrieve the the entity I am interested in with MetadataWorkspace.GetItem("MyDomain.TestEntity",DataSpace.OSpace), which gives me access to Properties, but none of the properties, of Properties, give me the name of the mapped db column, as specified with HasColumnName.
Also I am not clear what DataSpace.OSpace is and why my model is constructed in this space.
If Anyone can shed some light on this I would be grateful
UPDATE
Further to #Ladislav's comments. I discovered I can get the information as follows
For the class properties
ctx.MetadataWorkspace.GetItem<ClrEntityType>("MyDomain.TestEntity", DataSpace.OSpace)).Members
For the table properties
ctx.MetadataWorkspace.GetItem<EntityType>("CodeFirstDatabaseSchema.TestEntity",SSpace).Members
So given that I only know the type MyDomain.TestEntity and Memeber "Name". How would I go about to get "dbName". Can I always assume that my mapped class will be created in CodeFirstDatabaseSchema, om order to dynamically construct the identity to retrieve it from SSpace and how would I get to the correct Member in SSpace. Can I do something like
var memIndex = ctx.MetadataWorkspace.GetItem<ClrEntityType>("MyDomain.TestEntity", DataSpace.OSpace)).Members["Name"].Index;
var dbName = ctx.MetadataWorkspace.GetItem<EntityType>("CodeFirstDatabaseSchema.TestEntity",SSpace).Members[memIndex];

MetadataWorkspace contanis several containers specified by DataSpace. Interesting for you are:
CSpace - description of conceptual model (this should contain properties)
CSSpace - mapping of conceptual model to storage model (this should contain how classes / properties are mapped to tables / columns)

Related

Sulu: Entity has no field or association error

I'm following Sulu example here: https://github.com/sulu/sulu-workshop/
trying to set translations for custom entity type.
My entity file has getter for field "home_team" defined like:
/**
* #Serializer\VirtualProperty(name="home_team")
*/
public function getHomeTeam(): ?string
{
$translation = $this->getTranslation($this->locale);
if (!$translation) {
return null;
}
return $translation->getHomeTeam();
}
So field is not actually part of that entity, but of it's translation entity since it suppose to be translatable.
When I try to create new object of that entity type it works well. I can see in database that field values are stored well and I don't get any error.
But on overview page instead of list of all objects I get error:
[Semantical Error] line 0, col 73 near 'home_team AS': Error: Class App\Entity\MatchEvent has no field or association named home_team
Any idea what could be wrong here?
If you wanna see the translation in the listView you have to create a real translationEntity, like in the workshop project. In this post it is already explained, how to translate a custom entity correctly.
If you have already created your translationEntity you have to configure the relation of the translation to your main entity via a join. Here is an example in the workshop for this configuration.
Sulu uses optimised queries to create the list-object directly from the database. So the entity itself does not get hydrated or serialised for performance reasons. Thus your virtualProperty is never executed.

Using Orika in place of Spring Data Commons

There are several Spring Data projects like Neo4j that use the Spring Data Commons to build up a PersistentEntity/PeristentProperty (basically type info plus property geters and setters) and EntityConverter to roll from a native store to Java. This is what the SDN (Spring Data Neo4j) does plus it bundling BeanWrapper converters to make sure that certain property types are allowed for the Neo4j data structure.
Basically Java beans are stamped with a #NodeEntity annotation and the beans is decomposed on writes into nodes (think a bean with only simple properties) interlinked by relationship objects.
Wondering if I can do the same with Orika? Means identifying classes via an annotation and processing each property when complex recursively. For example:
#NodeEntity
class Software {
String name;
....
Organisation organisation;
....
}
#NodeEntity
class Organisation {
String name;
}
Should be rolled into 2 nodes each containing the property name and a relationship object (denotes Organisation as a member of Software).
Here is an example of an Orika ClassMapBuilder supporting custom annotations, I think you can adapt it to meet your needs.
Gist : AnnotationClassMapBuilder
For Node (or DBObject of MongoDB) you can use a custom property resolver, take a look at:
http://orika-mapper.github.com/orika-docs/advanced-mappings.html (ElementPropertyResolver)
Edit
Orika build mappers by class-map which are actually, just a collection of property-pair, property can be any thing which has name, type and setter or/and getter.
You can automatically create for each attribute in your beans an equivalent in Neo4J side, and let Orika build the mapper.
For example you can create a Person(name)->PrintStream mapper,
in which you create for each person's property (name) an equivalent that print data (System.out)
Example
final Builder name = new Property.Builder()
.name("name")
.type(String.class.getName())
.setter("append(\"My name : \").append(%s).append('\\n')");
factory.classMap(Person.class, PrintStream.class).fieldMap("name", name, false).add().register();
factory.getMapperFacade().map(person, System.out); // This print to default output stream, My name : xxxx

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: How to get mapped values?

Suppose I have a class Customer that is mapped to the database and everything is a-ok.
Now suppose that I want to retrieve - in my application - the column name that NH knows Customer.FirstName maps to.
How would I do this?
You can access the database field name through NHibernate.Cfg.Configuration:
// cfg is NHibernate.Cfg.Configuration
// You will have to provide the complete namespace for Customer
var persistentClass = cfg.GetClassMapping(typeof(Customer));
var property = persistentClass.GetProperty("FirstName");
var columnIterator = property.ColumnIterator;
The ColumnIterator property returns IEnumerable<NHibernate.Mapping.ISelectable>. In almost all cases properties are mapped to a single column so the column name can be found using property.ColumnInterator.ElementAt(0).Text.
I'm not aware that that's doable.
I believe your best bet would be to use .xml files to do the mapping, package them together with the application and read the contents at runtime. I am not aware of an API which allows you to query hibernate annotations (pardon the Java lingo) at runtime, and that's what you would need.
Update:
Judging by Jamie's solution, NHibernate and Hibernate have different APIs, because the Hibernate org.hibernate.Hibernate class provides no way to access a "configuration" property.

Retrieving Attribute names of an Entity in MS CRM 4.0

I am trying to retrieve the attribute name and type that exist in an entity, Dynamic Entity to be precise. I have the following code.
DynamicEntity contactEntity = new DynamicEntity();
contactEntity.Name = EntityName.contact.ToString();
Property t = null;
foreach (Property prop_Test in contactEntity.Properties)
{
Response.Write("<br/>Name : " + prop_Test.Name.ToString());
}
I am getting the properties count as 0.
Is it mandatory for me to pass an id to the contact entity. Because i am trying to map attributes from the entity to the attributes i get from an excel file. The end user themselves would be doing the mapping so all i need are the attribute name and type and nothing else. For instance in SQL we have the query
SELECT * FROM TABLE_NAME WHERE 1 <> 1
This query basically returns an empty resultset with only the fieldnames. That is what i am looking for here. Is it even possible ?
In your example above, the dynamic entity does not have any properties set on it. The dynamic entity is a special type in MS CRM that is used when you do not know the CRM type until runtime. If you add properties to the dynamic entity and run your example, you will get however many properties returned that you define.
In order to get the contact attributes, you will need to reference the CRM Metadata Service as explained in the SDK.
There is an example within this download in the HowTo section that shows how to get out the entity and attribute metadata.