简体   繁体   中英

Entity Framework Core: Assign default value in DB modal for nullable columns in Database when retrieving Data

I have an already existing DB table with nullable integer column called TotalAmount . While the DB model reflecting this table has the property TotalAmount as int [not nullable int=> int?].

Is there a way to assign a default value for this property if it's null when getting the data from this table?

I don't want to have int? field and I can't change the Column in the DB to make it not nullable.

You can have a constructor in the entity class for example. So whenever you create the class, a default value will be inserted for this field.

Example:

public class SomeEntityClass {
  public Guid Id {get; set;}
  public int TotalAmount {get;set;}
  
  public SomeEntityClass(){
    TotalAmount = 100;
  }  

}

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