Entity Framework persisted computed column woes - entity-framework-4.1

I recently updated a computed column to be persisted due to poor performance when querying it.
However now updates to child records throw this error
System.Data.SqlClient.SqlException
Internal Query Processor Error: The query processor could not produce a query plan. For more information, contact Customer Support Services.
Having an inner exception of
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types.
This happens with or without an index on the column.
FYI I have a configuration for the column thus:
Property(c => c.DisplayName).HasColumnName("DISPLAY_NM").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
Any workaround?
edit
The child element statement is pretty irrelevant - but here it is. Imagine entities Order, Company (an Order must have a Company). I create an Order with an un-changed Company and its the Company entity with the computed column that is causing the problem - it works fine without the persistence on the computed column (as expected there's 1 insert statement on Order and 0 update statements on Company)
I think this is the solution but unsure how to do it in EF

I solved similar problem by adding ID of related entity as property (essentialy exposed FK value in table), and when creating record, if I only assign id of related object to exposed FK property, everything works, related object is not needed.
You can see sample of entity having both related object and its ID mapped using EF fluid mapping here:
public ThingMap()
{
this.Property(t => t.Name)
.IsRequired()
.IsMaxLength()
.IsUnicode();
//// Table mappings
this.ToTable("Things", "go");
this.Property(t => t.Name).HasColumnName("Name");
this.Property(t => t.TypeId).HasColumnName("Type_Id");
//// References
this.HasRequired(t => t.Type)
.WithMany(t => t.Things)
.HasForeignKey(t => t.TypeId);
}

Related

Auditing with Hibernate Envers: How to Query When ID is not 'id'

With Hibernate Envers, you create a corresponding auditing table with a suffix of "_AUD" for each of your JPA entities and then you can query using AuditReader.
This AuditReader assumes that the ID of the Entity is id and that it has a getId() getter. In my case, all off my entities have differently named identifiers like userId and accountId, etc... all with varying dataTypes.
How can I create a pattern that reduces boilerplate code to retrieve auditing history data by id without knowing the fieldName of the id?
That is what AuditEntity.id() is for :)
AuditQuery query = getAuditReader()
.forRevisionsOfEntity( MyEntity.class. true, false )
.add( AuditEntity.id().eq( myEntityClassId ) );
You shouldn't need to know what property maps to your entity's identifier property because Envers will handle all the necessary equality / inequality checks between types and property mappings behind the scenes.
what about ?
getAuditReader().createQuery().forRevisionsOfEntity(MyEntity.class, false, false).add( AuditEntity.property("accountId").eq(12));

Perl DBIx::Class encounterd Object Json

I'm new to Perl and DBIx::Class.
This is how I get my meaning_ids from the table translation where language = 5:
my $translations = $schema -> resultset('Translation')->search({ language => '5'});
After it I'm trying to push my data from the database into my array data:
while ( my $translation =$translations->next ) {
push #{ $data }, {
meaning_id => $translation-> meaning
};
}
$self->body(encode_json $data );
If I do it like this, I get the following error:
encountered object
'TranslationDB::Schema::Result::Language=HASH(0x9707158)', but neither
allow_blessed , convert_blessed nor allow_tags settings are enabled
(or TO_JSON/FREEZE method missing)
But if I do it like that:
while ( my $translation =$translations->next ) {
push #{ $data }, {
meaning_id => 0+ $translation-> meaning
};
}
$self->body(encode_json $data );
I don't get the error anymore, but the meaning is not the number out of the database. It's way too big (something like 17789000, but only numbers till 7000 are valid).
Is there an easy way to tell Perl that meaning_id is an INT and not a string?
It's a bit hard without knowing your schema classes, but #choroba is right. The error message says $translation->meaning is an instance of TranslationDB::Schema::Result::Language. That's explained in DBIx::Class::Manual::ResultClass on CPAN.
I believe there is a relationship to a table called meaning, and when you call $translation->meaning what you get is a new result class. Instead you need to call $translation->meaning_id. Actually that would only happen in a join, but your code doesn't look like it does that.
It seems $translation->meaning returns an object. Using 0+ just returns its address (that's why the numbers are so high).
It looks like there's a relationship between your translation and meaning tables. Probably, the translation table contains a foreign key to the meaning table. If you look in the Result class for your translation class then you will see that relationship defined - it will be called "meaning".
As you have that relationship, then DBIC has added a meaning method to your class which retrieves the meaning object that is associated with your translation.
But it appears that the foreign key column in your translation table is also called "meaning", so you expect calling the "meaning" method gives you the value of the foreign key rather than the associated object. Unfortunately it doesn't work like that. The relationship method overrides the column method.
This is a result of bad naming practices. I recommend that you call the primary key for every table id and the foreign key that links to another table <table_name>_id - so the column in your translation table would be called meaning_id. That way you can distinguish between the value of the key ($translation->meaning_id) and the associated meaning object ($translation->meaning).
A work-around you can use if you can't rename columns, is to use the get_column method - $translation->get_column('meaning').

Automatically generated Entities from mysql database in Netbeans always fail to deploy

I am new to Java EE (and to Netbeans). I have am trying to automatically generate entity classes from my mysql database... For simple relationships it works, but for the following it always fails:
i get the following error:
Internal Exception: Exception [EclipseLink-7220] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The #JoinColumns on the annotated element [field tblExpandituresTranx] from the entity class [class entities.restaurant.TblContents] is incomplete. When the source entity class uses a composite primary key, a #JoinColumn must be specified for each join column using the #JoinColumns. Both the name and the referencedColumnName elements must be specified in each such #JoinColumn.. Please see server.log for more details.
I think... I have some error in my database or perhaps EclipseLink JPA tool is kaput!
please help!
Could be that your schema is upside down.
Or you could actually read the exception you're getting and figure out what it's telling you:
The #JoinColumns on the annotated element [field tblExpandituresTranx] from the entity class [class entities.restaurant.TblContents] is incomplete. When the source entity class uses a composite primary key, a #JoinColumn must be specified for each join column using the #JoinColumns. Both the name and the referencedColumnName elements must be specified in each such #JoinColumn
Looks like you've got an incomplete specification for the JOIN.
I solved the problem myself...
Apparently JPA has a problem with multiple primary keys in bridge tables. So, instead of having foreign keys as primaries I just converted them to unique indexed and everything worked just fine!! wuhu!!

Upgraded to the latest EF (4.1) from CTP - how do we override underscores generated in foreign keys

We recently upgraded our EF implementation from the CTP to the latest release of EF (4.1). We are now seeing an issue in that the foreign keys that are generated are now generated with an _ where previously there was none. As we have a couple of references to the previously generated names we find that our code is choking on the new format. Is there a way to override this behavior and generate foreign keys without the _?
You cannot override the behavior globally but you can override it for each generated foreign key.
Suppose that you have entity A with FK to B. You can use this fluent mapping to control naming of FK in the database:
modelBuilder.Entity<A>()
.HasRequired(a => a.B)
.WithMany(b => b.As)
.Map(m => m.MapKey("YourKeyName"));
This example expects A with required navigation property to B (FK is not nullable) and B with collection navigation property As containing all related A instances.

Errors creating generic relations using content types (object_pk)

I am working to use django's ContentType framework to create some generic relations for a my models; after looking at how the django developers do it at django.contrib.comments.models I thought I would imitate their approach/conventions:
from django.contrib.comments.models, line 21):
content_type = models.ForeignKey(ContentType,
verbose_name='content type',
related_name="content_type_set_for_%(class)s")
object_pk = models.TextField('object ID')
content_object = generic.GenericForeignKey(ct_field="content_type", fk_field="object_pk")
That's taken from their source and, of course, their source works for me (I have comments with object_pk's stored just fine (integers, actually); however, I get an error during syncdb on table creation that ends:
_mysql_exceptions.OperationalError: (1170, "BLOB/TEXT column 'object_pk' used in key specification without a key length")
Any ideas why they can do it and I can't ?
After looking around, I noticed that the docs actually state:
Give your model a field that can store a primary-key value from the models you'll be relating to. (For most models, this means an IntegerField or PositiveIntegerField.)
This field must be of the same type as the primary key of the models that will be involved in the generic relation. For example, if you use IntegerField, you won't be able to form a generic relation with a model that uses a CharField as a primary key.
But why can they do it and not me ?!
Thanks.
PS: I even tried creating an AbstractBaseModel with these three fields, making it abstract=True and using that (in case that had something to do with it) ... same error.
After I typed out that really long question I looked at the mysql and realized that the error was stemming from:
class Meta:
unique_together = (("content_type", "object_pk"),)
Apparently, I can't have it both ways. Which leaves me torn. I'll have to open a new question about whether it is better to leave my object_pk options open (suppose I use a textfield as a primary key?) or better to enforce the unique_togetherness...