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
}
Step 1 − First, create the console application from File → New → Project… Step 2 − Select Windows from the left pane and Console Application from the template pane. Step 3 − Enter EFCodeFirstDemo as the name and select OK. Step 4 − Right-click on your project in the solution explorer and select Manage NuGet Packages…
Accepted Answer. You cannot create views with EF Code First approach. If you want to create view then execute creation sql script in Seed method. But you'll still not be able to map entity to this view, except hacking model by creating and droping table with same name as your view will have.
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] ...");
}
I know old question but in case anyone in need. if you prefer a more simple flexible way. create a method in the Configuration.cs file. Then put your sql script in \App_Data directory that way you can put any SQL script you like in the .SQL file. Works fine in MVC 5.0, EF6.0
private void CreateProcedure(MvcAppDb context)
{
string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString() + @"/Procedures.sql";
Console.WriteLine(path);
FileInfo file = new FileInfo(path);
string script = file.OpenText().ReadToEnd();
context.Database.ExecuteSqlCommand(script);
}
Then add a call to the Configuration.cs and you all set.
protected override void Seed(MvcAppDb context)
{
CreateProcedure(context);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With