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

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.

Related

Manually setting annotation on generated migration using EF and MySql

I have a property that is in my class that is not the primary key that I want to auto increment. The primary key is a GUID so I can still use the auto increment function on another column in the table. Also I can't change the primary key to int as the GUID key is defined in a base class. I can manually add the .Annotation("MySQL:AutoIncrement", true) to the property in the generated migration but I'm concern about editing the migration causing future issues. I found what would be the answer via the .AddAnnotation(,) method but it doesn't created the desired results.
Also [DatabaseGenerated(DatabaseGeneratedOption.Identity)] doesn't produce the desired result.
I was hoping this:
builder.Entity<Editor>().Property(p => p.CreatorId).ValueGeneratedOnAdd().Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw;
builder.Entity<Editor>().Property(p => p.CreatorId).Metadata.AddAnnotation("MySQL:AutoIncrement", true);
Would make this:
migrationBuilder.CreateTable(
name: "editor",
columns: table => new
{
CreatorId = table.Column<int>(nullable: false).Annotation("MySQL:AutoIncrement", true)
...
MySql.Data.EntityFrameworkCore: 8.0.18.0
Microsoft.EntityFrameworkCore: 2.2.4
After using DotPeek to look at the code for MySql.Data.EntityFramework it seems to not be possible to reach the desired affect with fluentApi or attributes as it will only add the annotation if it's the primary key. Regardless of if it's possible in the database.

Fluent NHibernate Schema output with errors when using list

I have two tables which are Many-To-One mapped. However, it is important to maintain the order of the second table, so when I use automapping, Fluent automapper creates a bag. I changed this to force a list by using this command:
.Override(Of ingredients)(Function(map) map.HasMany(Function(x) x.PolygonData).AsList())
(VB.NET syntax)
So I say "AsList" and instead of using a bag, the mapping xml which gets generated contains a list now. Fine so far. However,
the statement generated cannot be handled by MySQL. I use MySQL55Dialect to create the statements and I use exactly that version. But it creates the following create:
create table `ingredients` (
Id INTEGER NOT NULL AUTO_INCREMENT,
Name FLOAT,
Amout FLOAT,
Soup_id INTEGER,
Index INTEGER,
primary key (Id)
)
It crashes because of the line "Index INTEGER," but I don't know what to do here. Any ideas?
Thanks!!
Best,
Chris
I would suspect that Index could be a keyword for MySQL. To avoid such conflict, we can define different Index column name (sorry for C# notation)
HasMany(x => x.PolygonData)
.AsList(idx => idx.Column("indexColumnName").Type<int>())

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!!

Entity Framework persisted computed column woes

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);
}

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...