Is it possible to use Code First
to create a database function in sql server?
Like
CREATE FUNCTION [dbo].[fnIsPaid] ...
Here is how I have worked it out based on ChrFin's suggestion. I marked it as the answer. But let me keep a more detailed record here.
In the Package Manager Console,
Add-Migration AddFnIsPaid`.
This will create a DbMigration
class prefixed with timestamp.
In this migration class, I have a create script and drop script for Up()
and Down()
method:
public partial class AddFnIsPaid : DbMigration
{
public override void Up()
{
Sql(_createFunctionScript);
}
public override void Down()
{
Sql(DropFunctionScript);
}
#region SQL Scripts
private readonly string _createFunctionScript = string.Concat(
"CREATE FUNCTION [dbo].[fnIsPaid] ",
"(",
...
") ",
"RETURNS bit ",
"AS ",
"BEGIN ",
...
"END"
);
private const string DropFunctionScript = "DROP FUNCTION [dbo].[fnIsPaid]";
#endregion
}
No, you can only tell it to map CRUD actions to stored procedures (EF 6+) with e.g.:
modelBuilder
.Entity<Post>()
.MapToStoredProcedures();
But you can execute custom SQL in your migration:
public override void Up()
{
Sql("CREATE FUNCTION [dbo].[fnIsPaid] ...");
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments