Code First Default Values

CodeXennial 26 Reputation points
2021-09-10T03:18:38.207+00:00

How do I set a default value in code first?

[Required]
[DefaultValue(-1)]
public int PostStatusID { get; set; }

How do I set the default value on deletion?

    builder
        .Entity<Post>()
        .HasOne(e => e.Status)
        .WithOne(e => e.AssignedPost)
        .OnDelete(DeleteBehavior.SetDefault);

This code doesn't work.

Cascade is not going to work because I do not want a post deleted just because a status was deleted. So I need another option. I can't set the value to null, so I need to set it to a default value, or I need to prevent a status from being deleted while a post is referencing it as a foreign key.

OnDelete(DeleteBehavior.Restrict)

Is restrict going to prevent a status from being deleted while a post is referencing it? The description of this value isn't clear to me.

Developer technologies .NET Entity Framework Core
0 comments No comments
{count} vote

1 answer

Sort by: Most helpful
  1. Jack J Jun 25,296 Reputation points
    2021-09-10T09:43:30.583+00:00

    @CodeXennial , you could try the following code to set the default value in code first.

    public class Student  
        {  
      
            [Key]  
            public int Id { get; set; }  
            public int PostStatusID { get; set; }  
      
              
            public string Name { get; set; }  
      
        }  
      
        public class StudentContext:DbContext  
        {  
            public DbSet<Student> students { get; set; }  
      
            protected override void OnModelCreating(ModelBuilder modelBuilder)  
            {  
                modelBuilder.Entity<Student>()  
                    .Property(b => b.PostStatusID)  
                    .HasDefaultValue(-1);  
            }  
            protected override void OnConfiguring(DbContextOptionsBuilder builder)  
            {  
                builder.UseSqlServer("connstr");  
            }  
        }  
    

    Result in database design:

    131030-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.