Symfony - Add a column to a table without losing already generated classes - symfony1

How can I add a column to a Database table without overwriting the classes already generated? (Doctrine) What files do I have to edit?
If I simply add the column in the database, I can't use the set and get functions of Doctrine ORM.

Use doctrine migrations. It allows you to modify your schema, update the database and your model without also losing the existing data in your database (in case it is relevant).
http://www.symfony-project.org/doctrine/1_2/en/07-Migrations
Applicable for symfony 1.4 too

You should never edit the base classes (BaseFoo.class.php) as these get overwritten everytime you generate the models from the schema. The other files are never overwritten so it's safe to edit.

Doctrine 1.2:
Go to models folder, open generated class that reflects table to which you have added a column. Add
$this->hasColumn('id', 'integer', 8, array(
'type' => 'integer',
'autoincrement' => true,
'primary' => true,
'length' => '8',
));
to setTableDefinition method.
Note, that your changes will be overwritten on generate-models, so make sure you populate it to YAML/DB schema
See Doctrine Models Definition Manual for reference.
Doctrine 2
Samples given for Annotations Driver, see Doctrine2 manual for other XML and YAML drivers
Just add new property to your #Entity class with #Column annotation on it:
/** #Column(type="integer", name="new_column") */
protected $new_column;

Related

EF Core 7.0 Migration Ignores DeleteBehavior.NoAction

I have an EF Core model with a root entity type that has multiple one-to-many relationships with other entity types. Some of these child types also relate to each other, so I understand that I need to take precautions to avoid circular reference issues when deleting a root entity instance.
Without any explicit model builder configuration between the root entity type and its child types, the resulting migration includes clauses like this:
migrationBuilder.AddForeignKey(
name: "FK_Merchants_Platforms_PlatformId",
table: "Merchants",
column: "PlatformId",
principalTable: "Platforms",
principalColumn: "Id");
If I attempt to run this migration, I see the following error:
In an attempt to solve this problem, I added explicit model builder configurations, which force NoAction on delete. Here's one example, applied to the child entity type:
builder
.HasOne(e => e.Platform)
.WithMany()
.HasForeignKey(e => e.PlatformId)
.OnDelete(DeleteBehavior.NoAction);
The above explicit change has no effect on the generated migration. However, if I change the DeleteBehavior to something other than NoAction, it produces the desired effect:
builder
.HasOne(e => e.Platform)
.WithMany()
.HasForeignKey(e => e.PlatformId)
.OnDelete(DeleteBehavior.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Merchants_Platforms_PlatformId",
table: "Merchants",
column: "PlatformId",
principalTable: "Platforms",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
Based on what I am seeing above, I guess NoAction is the default configuration and is implicitly applied when a migration is executed. However, if that's the case, it is not clear why I am seeing runtime migration errors.
Can anyone suggest the correct model builder configuration to force NoAction in the generated migration?

How does Breeze handle database column defaults?

I can't find any info about this in the documentation, so I will ask here. How does breeze handle database column defaults? I have required columns in my database, but there are also default static values supplied for these in the database column definitions. Normally, I can insert null into these columns, and the new records will get the default. However, breeze doesn't seem to be aware of database column defaults, and the entities that have null in these columns fail validation on saving.
Thanks,
Mathias
Try editing the edmx xml by adding StoreGeneratedPattern = "Computed" attribute to the column with default value in the DB.
Edit:
Actually, before doing editing the xml, try setting the StoreGeneratedPattern property to Computed in the model editor itself.
Update:
This was fixed in Breeze 1.4.6 ( or later), available now.
Original Post:
There is currently in a bug in Breeze that should be fixed in the next release, out in about week. When this fix gets in then breeze will honor any defaultValues it finds in the EntityFramework data model.
One problem though is while it is easy to get 'defaultValues' into a Model First Entity Framework model via the properties editor, it's actually difficult to get it into a Code First EF model, unless you use fluent configuration. Unfortunately, EF ignores the [DefaultValue] attribute when constructing Code First model metadata.
One workaround that you can use now is to poke the 'defaultValue' directly onto any dataProperty. Something like:
var customerType = myEntityManager.metadataStore.getEntityType("Customer");
var fooProperty = customerType.getProperty("foo");
fooProperty.defaultValue = 123;

How to create model from database preserving 'default' constraint values

My existing table contains nearly 50 columns, most of them have the 'default' constraint.
I have created the model based on this database table. All seemed ok, until i tried to insert a new row. I've got a sql server error stating that some column cannot be null. It appears that creating a model from the database did not preserve the default constraints.
I edited the model manually adding all the defaults and after that inserting didn't fail.
So my question is, how do i create a model that automatically picks up default constraints associated to the columns?
Using mvc4, visual studio 2010, sql server 2008 r2.
Google search didnt make sense as all the people seemed to be talking about something different than what i need.
Pretty sure my answer from Possible to default DateTime field to GETDATE() with Entity Framework Migrations? will work for you too. By using a modified MigrationCodeGenerator class and iterating through the operations list you can update the columns and add DefaultValueSql values based on whatever rules you need.
Well, you have a number of options. You could set the default values in the Model's default constructor. I think this is the better solution.
If you must have the default constraints in your database you could do set defaultValueSql in your data migrations like this:
AddColumn("ExistingTable", "NewColumn",c => c.Int(nullable: false, defaultValueSql: "0"));

How do I avoid automatic schema modifications when working with legacy databases using Grails?

Grails does automatic schema modifications (including index/foreign key updates) when changing the domain model. This is usually fine, but when working with legacy databases I would like to completely disable all table modifications.
How do I instruct Grails never to modify the table structure (including indexes and foreign key constraints)?
This is how I've currently setup the mapping:
class ClassName {
String string1
String string2
AnotherClass anotherClass
static mapping = {
version(false)
table("legacy_table")
string1(column: "some_legacy_field_1")
string2(column: "some_legacy_field_2")
anotherClass(column: "another_class_id", nullable: true, ignoreNotFound: true)
}
}
The dataSource defined in /grails-app/conf/DataSource.groovy has a dbCreate property, which can be set to validate to check that the schema matches the domain model without changing it in any way.
More details here:
http://grails.org/doc/latest/guide/3.%20Configuration.html#3.3%20The%20DataSource
As mentioned before, the property dbCreate is the one you use to specify how the database would be altered every time there are changes done in the Domain classes. I would suggest removing this property entirely as Burt suggested, so Hibernate does not control how the database is updated since that could cause certain conflicts depending on the changes you make to your domain classes.
The way I manage the database changes in our project is by using a database migration, I recommend using Liquibase, there is plug in for Grails that works perfectly, it is easy to use and offer great flexibility.

Where is modelBuilder.IncludeMetadataInDatabase in EF CTP5?

With CTP4, I used to be able to do the following (as suggested by ptrandem):
modelBuilder.IncludeMetadataInDatabase = false
With this line of code, EF doesn't create the EdmMetadata table in my database, and doesn't track model changes.
I was unable to find a way to accomplish this in the new CTP5, so now every time I change my model, I get this:
The model backing the 'MyContext'
context has changed since the database
was created. Either manually
delete/update the database, or call
Database.SetInitializer with an
IDatabaseInitializer instance. For
example, the
DropCreateDatabaseIfModelChanges
strategy will automatically delete and
recreate the database, and optionally
seed it with new data.
So, does everybody know where is the IncludeMetadataInDatabase property in CTP5? Thanks.
CTP5 includes a very cool feature called Pluggable Conventions that can be used to Add/Remove conventions. IncludeMetadataInDatabase has been removed and being replaced with a
pluggable convention that does the same thing for you:
modelBuilder.Conventions
.Remove<System.Data.Entity.Database.IncludeMetadataConvention>();
The equivalent in CTP5 to switch off initializer logic: In your Application_Start in Global.asax, enter the following:
System.Data.Entity.Database.DbDatabase.SetInitializer<MyDBContext>(null);
In EF 4.1
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<IncludeMetadataConvention>();
}
Have been looking for this all over, and I had to find the answer right after posting my question, DUH. Right from the ADO.NET team blog:
In CTP5 we have removed the need to
perform additional configuration when
mapping to an existing database. If
Code First detects that it is pointing
to an existing database schema that it
did not create then it will ‘trust
you’ and attempt to use code first
with the schema. The easiest way to
point Code First to an existing
database is to add a App/Web.config
connection string with the same name
as your derived DbContext (...)

Resources