How can I specify a Check Constraint in EF4 CodeFirst.
Example: I have a string property for which I can have only specific values.
EF code first doesn't have any equivalent for check constraints. If you want to have check constraint in the database you can either use custom database initializer and execute custom SQL to alter table and add check constraint (I described similar approach for unique index here) or if you are already using EF code first migrations you can add constraint creation to your Up method in code based migration.
Related
How can I add a unique contraint to the AspNetUsers.UserName column using Entity Framework migrations? It seems like a jungle to me figuring out how the initial Identity tables are configured.
To make the column unique you can use Data Annotations and the attribute [Index(IsUnique=true)] in your code. Please see this Post by #juFo for more information.
I would like to generate multicolumn unique constraints in Grails such as one defined in following entity class
class Relationship {
Element source
Element destination
Type type
// other properties omitted
static constraints = {
type unique: ['source', 'destination']
}
}
but I don't want to have that constraint active during the validation as it consumes lot of resources (see alternative to grails multicolumn unique constraint (optimistic inserts)) for stats.
Is there any way to achieve that? What are the alternatives to generate the unique index automatically (with checking for existing one)?
I've done this in an app where I knew that a column's values were unique based on how they were generated, so I didn't want Grails to run a select query during validation, but wanted the database check just in case something weird happened.
I would do this using a database migration. Add whatever constraints and indexes you like, in addition to the updates that are needed to keep the code and database in sync (e.g. adding/removing columns or tables, changing column types, etc.)
I forced to work with database where tables haven't auto increment. And I can't alter it. I want to insert entity using Entity Framework. I create an object of this entity and manually set it's Id field (primay key) and then make Add and SaveChanges. But I see in log, that EF clear the value of DbParameter for Id field. Is there any solution for this?
You can add an annotation of fluent configuration to tell EF the keys are manual. See Entering keys manually with Entity Framework. You could also add a custom convention to handle globally: Convention for DatabaseGeneratedOption.None
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"));
Using EF code first, we have a db seeding framework that uses dependency injected Db initializers and seeders to populate a dev db with sample test data.
Some of these seeding operations need to import a lot of data, so for a couple of tables, we use actual SQL files with INSERT statements. For some of those insert statements, foreign keys must be diabled then re-enabled:
ALTER TABLE [Schema].[TableName] NOCHECK CONSTRAINT [TableName_FkPropertyName]
-- perform a block of inserts
ALTER TABLE [Schema].[TableName] CHECK CONSTRAINT [TableName_FkPropertyName]
I just updated from EF 4.2 to EF 4.3 and noticed that these no longer work. An examination of the db created by EF shows that the FK's are now named differently:
FK_CodeFolder1.Table1Name_CodeFolder2.Table2Name_DbFkColumnName
Is there any way to remove this naming convention and go back to the original? If not, how is this not a known issue or breaking change?
Update after Ladislav's Reply
Ladislav is right, my above explanation of the new naming pattern was not quite right. I have updated it. The part preceding the . was not the full namespace, but it was the name of a folder in the entity model project. So if I had an entity WidgetAbc in folder AggregateSet1, the fk pattern fragment would be AggregateSet1.WidgetAbc, not just WidgetAbc.
Why do you think it is an issue or breaking change? IMHO it is EF internal behavior - you are using code first and in this approach you were not supposed to work directly with database and especially you were not supposed to base your custom database scripts on hardcoded names because you don't have control over their generation.
I don't think you can revert the behavior but you can start using migrations and code your table definitions - AddForeignKey method should allow you naming your FK constraint.
Btw. I see different naming pattern of FK constraints in EFv4.3:
FK_DependentTableName_PrincipalTableName_FKColumnName