set identity and computed properties in entity framework without triggers
TRANSCRIPT
-
28/3/2014 Set Identity and Computed Properties in Entity Framework Without Triggers
http://blog.devart.com/set-identity-and-computed-properties-in-entity-framework-without-triggers.html 1/9
Set Identity and Computed Properties in EntityFramework Without Triggers
Posted by dotConnect Team on August 9th, 2011
This article deals with the following:
StoreGeneratedPattern
IdentityComputed
DefaultValue
InsertNullBehaviourExample
Conclusion
StoreGeneratedPattern
Entity Framework contains an excellent functionality of server-generated columns of the entity that is intendedfor defining the primary key values on the database side, concurrency check and so on. This is done by setting
StoreGeneratedPattern of columns of the EF-model storage part (SSDL) to either Identity or Computed.
Identity
In a number of databases (Microsoft SQL Server, MySQL, PostgreSQL, SQLite),
StoreGeneratedPattern.Identity of the columns primary key is defined by the EF-designer when a model is
created against the database and if these columns are made auto-increment in the database. Oracle does nothave any standard way of making a column auto-increment, thus, in the database, the users have to create a
sequence and the BEFORE INSERT trigger that defines the value of an auto-increment column based on the
sequence; when the model is created, the users have to set the value of StoreGeneratedPattern manually in the
model editor.
Computed
In most cases, supporting this functionality involves writing UPDATE-triggers in the database, which takes
time and requires knowledge of a specific programming language other than SQL, for example, PL/SQL in
-
28/3/2014 Set Identity and Computed Properties in Entity Framework Without Triggers
http://blog.devart.com/set-identity-and-computed-properties-in-entity-framework-without-triggers.html 2/9
Oracle.
DefaultValue
To facilitate and speed up the process of development as well as to increase its flexibility, we have provided
the users of our EF-providers for Oracle, MySQL, PostgreSQL and SQLite with a capability that, in simple
cases, obviates the need to write INSERT and UPDATE triggers and to set a default value for columns in the
database. This can also be useful when you need, if possible, to use existing objects rather than modify thedatabase. Now, you can assign values to columns by specifying database functions in the columns
DefaultValue attribute in the storage part of the EF model (SSDL).
If you use Entity Data Model Designer, you will need to edit the models XML using an XML editor. Bear in
mind that the DefaultValue standard attribute is checked by EF-validation and that is why it cannot be used to
call a DB-function. For that reason, we have introduced the new custom devart:DefaultValue SSDL attribute
(if you need to edit manually the EDMX file, do not forget to add the attribute
xmlns:devart=http://devart.com/schemas/edml/StorageSchemaExtensions/1.0 to the tag Schema in SSDL).The devart:DefaultValue attribute does not trigger the type consistency check, so you can use a wider range ofdefault values, like CURRENT_TIMESTAMP or MY_SEQUENCE.NEXTVAL.
If you use Devart Entity Developer, you will be able to set the value for DefaultValue in the designer, and it
will store this value correctly either in the DefaultValue attribute or in devart:DefaultValue , as required.
InsertNullBehaviour
To use this functionality, you need to configure the EF-provider. For more information on the specifics ofconfiguration, see New Features of Entity Framework Support in dotConnect Providers; for the purpose of
the present article we shall review a small example that shows how to customize the DefaultValue processingbehavior. In this example, we deal with the dotConnect for Oracle provider, but the procedure is identical forMySQL, PostgreSQL, and SQLite.
New features are configured in the EntityProviderConfig class. This class is available in theDevart.Data..Entity assembly. Dont forget to add this Devart.Data.
.Entity.dll assembly as Reference for the corresponding Entity Framework version (supportfor the new functionality is available for EF v1 and v4.x).For more information on capabilities of InsertNullBehaviour, see here.
Example
As an example, we shall use a table in Oracle, in which we want to define the behavior of the store generatedcolumns in the model rather than create triggers. For the purpose of this example, we also suppose that we
already have a sequence (MY_SEQUENCE) and a database function (MY_FUNCTION) that we can nowuse. Lets demonstrate all the capabilities within a single example.
var config = OracleEntityProviderConfig.Instance; config.DmlOptions.InsertNullBehaviour = InsertNullBehaviour.InsertDefaultOrNull;// orconfig.DmlOptions.InsertNullBehaviour = InsertNullBehaviour.InsertDefaultOrOmit;
-
28/3/2014 Set Identity and Computed Properties in Entity Framework Without Triggers
http://blog.devart.com/set-identity-and-computed-properties-in-entity-framework-without-triggers.html 3/9
Below is the script for creating the table:
XML-representation of the entity in the storage model (SSDL):
Now we shall modify mapping by defining the following rules:
The ID column, which is the primary key, will be defined through the value of the sequenceMY_SEQUENCE on INSERT.The FunctionGeneratedValue column will be defined through the call of the user-defined function
MY_FUNCTION() on INSERT.
The ModifiedBy will be defined through the system database function USER on INSERT andUPDATE.
The LastModified column will be defined through the system database function
CURRENT_TIMESTAMP on INSERT and UPDATE. This column will be used for concurrencycheck, so we need to set ConcurrencyMode=Fixed for this column in the conceptual model.
XML SSDL after modification is shown below:
CREATE TABLE "Products" ( ID NUMBER(9) PRIMARY KEY, "ProductName" VARCHAR2(160) NOT NULL, "Price" NUMBER(10, 2), "FunctionGeneratedValue" NUMBER NOT NULL, "ModifiedBy" VARCHAR2(30) NOT NULL, "LastModified" TIMESTAMP NOT NULL)
-
28/3/2014 Set Identity and Computed Properties in Entity Framework Without Triggers
http://blog.devart.com/set-identity-and-computed-properties-in-entity-framework-without-triggers.html 4/9
Below shown is an example of C# code:
To monitor queries sent to the server, we recommend that you use Devart dbMonitor, a free tool, that iscompatible with Devart EF-providers. However, the use of this monitor is recommended only on the stage of
development and debugging of the application, since its use causes a drop in performance.
Shown below is SQL generated on INSERT:
Shown below is SQL generated on UPDATE:
// Here we turn on the monitoring of interaction with the database through dbMonitorvar mon = new Devart.Data.Oracle.OracleMonitor { IsActive = true }; // Here we configure the EF-provider, so that the default values defined in the model are used var config = OracleEntityProviderConfig.Instance;config.DmlOptions.InsertNullBehaviour = InsertNullBehaviour.InsertDefaultOrNull; // Here we create the context and perform insert and update of the entity using (var ctx = new Entities()) { Products product = new Products() { ProductName = "Gadget", Price = 220.25 }; ctx.Products.AddObject(product); ctx.SaveChanges(); // INSERT product.Price = 199.99; ctx.SaveChanges(); // UPDATE}
DECLARE updatedRowid ROWID;BEGININSERT INTO "Products"(ID, "FunctionGeneratedValue", "ModifiedBy", VALUES (MY_SEQUENCE.NEXTVAL, MY_FUNCTION(), USER, CURRENT_TIMESTAMPRETURNING ROWID INTO updatedRowid;OPEN :outParameter FOR SELECT ID, "FunctionGeneratedValue", "ModifiedBy"END;
DECLARE updatedRowid ROWID;BEGINUPDATE "Products" SET "ModifiedBy" = USER, "LastModified" = CURRENT_TIMESTAMP, "Price" WHERE ID = :p1 AND "LastModified" = :p2RETURNING ROWID INTO updatedRowid;OPEN :outParameter FOR SELECT "ModifiedBy", "LastModified" FROM "Products"
Tweet
2
2
-
28/3/2014 Set Identity and Computed Properties in Entity Framework Without Triggers
http://blog.devart.com/set-identity-and-computed-properties-in-entity-framework-without-triggers.html 5/9
Conclusion
As we have seen, this functionality is extremely simple to use. If you, as yet, do not use Entity Developer,
whose EF-version is shipped with our EF-providers, consider doing so, since it allows modifying the storagemodel much more easily and more conveniently than a standard EDM designer does and hence is a more
suitable tool for this purpose. Nor should you forget to monitor SQL being sent on the development stage, so
that you can be sure that everything works as intended.
See also
Oracle 12c Support and More New Features in New Versions of Devart Products
Model-Defined Functions in Entity DeveloperEnhanced Entity Framework Spatials support for Oracle, MySQL and PostgreSQL
Entity Framework 6 Support for Oracle, MySQL, PostgreSQL, SQLite, DB2 and Salesforce
New Features in Entity Developer 5.0
2 Responses to Set Identity and Computed Properties in Entity FrameworkWithout Triggers
1. Max1ce Says: November 15th, 2011 at 5:30 pm
How would you use the DefaultValue in a code-first approach without using the designer?
2. Shalex Says: November 17th, 2011 at 1:25 pm
Microsoft does not allow setting default value in the current version of EF Code-First fluent mapping.
There are several suggestions about the default value support at official Entity Framework UserVoice:http://data.uservoice.com/forums/72025-ado-net-entity-framework-ef-feature-
suggestions/suggestions/1050341-allow-setting-default-values-from-model?ref=title
http://data.uservoice.com/forums/72025-ado-net-entity-framework-ef-feature-suggestions/suggestions/1501715-more-options-in-code-first-db-generation?ref=title
Search for:
Search
Teams
ALM TeamDAC Team
dbForge Team
dotConnect TeamSubscribe by e-mail
Enter your email address:
END;
-
28/3/2014 Set Identity and Computed Properties in Entity Framework Without Triggers
http://blog.devart.com/set-identity-and-computed-properties-in-entity-framework-without-triggers.html 6/9
Subscribe
Tags
ADO.NET Android development C++Builder Code-First Migrations code comparison Code First code
review command line Continuous Integration database designer database development database
diagram database project data compare data import Delphi Delphi XE2 Delphi XE5 EF
Tips and Tricks Entity Framework Full-Text Search how to Intellisense iOSdevelopment large databases LINQ LINQ to SQL Many-to-Many Mapping MSBuild MySQLMySQL GUI client NHibernate Oracle Performance PostgreSQL query builderRad Studio RAD Studio XE2 RAD Studio XE5 Review Assistant schema compareSQLite SQL Server synchronize database Whats New in Review Assistant 2.0
Devart Blog / Teams / dotConnect Team / Set Identity and Computed Properties in Entity Framework
Without Triggers
Devart Blog
Products DownloadsPurchase
Support BlogCompany
ProductsDatabase Tools
SQL Server Tools
MySQL ToolsOracle ToolsPostgreSQL Tools
.NET Database Connectivity
ADO.NET Data ProvidersORM Solutions
Developer Tools
Coding Assistance
Delphi Database Connectivity
Delphi Data Access Components
-
28/3/2014 Set Identity and Computed Properties in Entity Framework Without Triggers
http://blog.devart.com/set-identity-and-computed-properties-in-entity-framework-without-triggers.html 7/9
dbExpress Drivers
Support
Submit Request
View ForumsDocumentation Center
Ordering FAQs
High Five ProgramEventsCompany
About UsNewsCustomers
PartnersResellersContacts
Contact Form
Social
Facebook Twitter Google+ Linkedin YouTubeCopyright 1998 - 2014 Devart. All rights reserved.
ProductsForums
SupportCompany
Site Map
SQL Server Tools
dbForge Studio for SQL Server Updated!SQL Complete Updated!
Compare Bundle for SQL ServerSchema Compare for SQL ServerData Compare for SQL Server
Query Builder for SQL ServerSQL Azure BackupSQL Decryptor
dbForge Fusion for SQL Server New!
MySQL Tools
dbForge Studio for MySQL Updated!
Compare Bundle for MySQLSchema Compare for MySQL Updated!Data Compare for MySQL Updated!
Query Builder for MySQL Updated!
-
28/3/2014 Set Identity and Computed Properties in Entity Framework Without Triggers
http://blog.devart.com/set-identity-and-computed-properties-in-entity-framework-without-triggers.html 8/9
dbForge Fusion for MySQL
Oracle Tools
dbForge Studio for Oracle Updated!Compare Bundle for OracleSchema Compare for Oracle Updated!
Data Compare for Oracle Updated!dbForge Fusion for Oracle Updated!
PostgreSQL Tools
Data Compare for PostgreSQL
Developer Tools
Review Assistant Updated!Code Compare Updated!LINQ Insight Updated!
T4 Editor Updated!SecureBridgedbMonitor
ADO.NET Data Providers
dotConnect for OracledotConnect for MySQL
dotConnect for PostgreSQLdotConnect for SQLitedotConnect for Salesforce Updated!
dotConnect for DB2 New!dotConnect for SQL ServerdotConnect Universal
ORM Solutions
LinqConnectEntity Developer Updated!
Delphi Data Access Components
EntityDAC Beta!UniDACODAC
SDACMyDACIBDAC
PgDACLiteDAC
VirtualTable
dbExpress Drivers
-
28/3/2014 Set Identity and Computed Properties in Entity Framework Without Triggers
http://blog.devart.com/set-identity-and-computed-properties-in-entity-framework-without-triggers.html 9/9
Oracle driverSQL Server driverMySQL driver
Interbase/Firebird driverPostgreSQL driverSQLite driver
ForumsRequest SupportDocumentation Center
Ordering FAQs
About UsNews
CustomersPartnersResellers
ContactsContact Form