简体   繁体   中英

Execute stored procedure with a default parameter

I need to use a stored procedure with three parameters. The second parameter is a default value. I am not allowed to modified the stored procedure. When I try to execute the stored procedure using Entity Framework, I am passing the first and the third parameters. And I am getting the error that the third parameter is not provided.

This is the signature of the stored procedure:

[dbo].[sp_CreateTest] 
      @Par1 NVARCHAR(25),
      @Par2 NVARCHAR(50) = 'Test',
      @Par3 NVARCHAR(50)

I am trying to execute it like this:

List<SqlParameter> parameters = new List<SqlParameter>();
parameters.Add(new SqlParameter("@Par1", "Parameter1 data"));
parameters.Add(new SqlParameter("@Par3", "Parameter3 data"));

testEnt.Database.ExecuteSqlCommand("exec dbo.sp_CreateTest @Par1, @Par3", parameters.ToArray());

you can use "Default" as parameter in place of second parameter. ie

"exec dbo.sp_CreateTest @Par1,DEFAULT,@Par3"

One method is to use named parameter notation instead of positional notation so that default values are used for those not specified. This will also avoid tight coupling to parameter ordinals.

testEnt.Database.ExecuteSqlCommand("exec dbo.sp_CreateTest @Par1=@Par1, @Par3=@Par3", parameters.ToArray());

Example:

 public class BlogContext : DbContext
 {

 public DbSet<Post> Posts { get; set; }

 public BlogContext(DbContextOptions<BlogContext> options) : base(options)
 {
 }

 protected override void OnModelCreating(ModelBuilder modelBuilder)
 {
     base.OnModelCreating(modelBuilder);

     modelBuilder.Entity<Post>().Property(p => p.Text).HasDefaultValue("Default");
 }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM