2

I am using SQL server for database while developing in ASP.NET . In my database table, most of the columns are NOT NULL and have a set default value. I am also using Entity Framework.

My Model(class) currently looks like this:

public partial class INV
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public INV()
    {
        this.INVAttachments = new HashSet<INVAttachment>();
    }

    public int ID { get; set; }
    public string SUPPROD { get; set; }
    public string TYPE1 { get; set; }
    public int MAXQTY { get; set; }
    public decimal ROP { get; set; }
    public int ROQ { get; set; }
    public decimal SSL { get; set; }
    public Nullable<System.DateTime> SYSDATE { get; set; }
    public Nullable<System.DateTime> MAINT_DATE { get; set; }


    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public ICollection<INVAttachment> INVAttachments { get; set; }
} 

The user submits a form, and inside the form, most of fields are actually optional. But in the database, the columns are not null.

When I POST the form over to the server side, the INV object representation has null for the properties of the INV object. Below is a WebAPI function to handle the POST and save the INV object in the database.

    [ResponseType(typeof(string))]
    public async Task<string> PostINV(INV iNV)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                //return BadRequest(ModelState);
                return "badRequest";
            }

            db.INVs.Add(iNV);
            await db.SaveChangesAsync();

            //codes written here


        }catch (Exception ex)
        {
            return "";
        }
    }

The above function is now returning system.data.entity.validation.dbvalidationerror for the INV entity because the properties for INV is required, but the object that I POST over contain NULL values.

My question is it possible to make sure the database columns remain NOT NULL but at the same time, I don't want my Model or Class to use Nullable types? Is it a matter of using a constructor for my class to set default values ?

jin cheng teo
  • 195
  • 1
  • 13
  • 1
    Suggest you start by reading [What is ViewModel in MVC?](https://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Aug 06 '18 at 03:20
  • Well you have a problem. you have a constraint on your DB to enforce a value, and your model accepts nulls. You are either going to have to make up values for your DB, make your db fields nullable, or enforce the constraint on the user form. .Net or SQL will not be able to read your mind – TheGeneral Aug 06 '18 at 03:21
  • @TheGeneral, how does one make up values for DB ? Is it done by defining a constructor or a method on the model? – jin cheng teo Aug 06 '18 at 03:41
  • This link might help you [Code first default value](https://stackoverflow.com/questions/19554050/entity-framework-6-code-first-default-value) – Danushka Amith Weerasingha Aug 06 '18 at 03:56
  • Are you using Code-First, or is this a Database-first model using an EDMX file? – Tieson T. Aug 06 '18 at 05:29
  • @TiesonT. This is database first. – jin cheng teo Aug 06 '18 at 05:31
  • @StephenMuecke, may I ask you something more... Because I don't understand something else... When I use a ViewModel which contains a subset of all the properties in the original (domain) model. then when I POST the viewModel over, what happens with the rest of the properties that are defined in the original (domain) model ? those other properties are automatically processed by ASP.NET ? – jin cheng teo Aug 06 '18 at 06:56
  • The view model includes only the properties you need in the view, and in your POST method, you get the original data model from the db (based on the ID), and update just the properties of the data model you want, then save the data model. –  Aug 06 '18 at 06:58
  • @StephenMuecke, is it also the same process when I want to INSERT INTO the database ? Or is it for insert into, I have to declare some default values if the database column is not null ? – jin cheng teo Aug 06 '18 at 07:31
  • Yes, except that you would just initialize a new instance of your data model and set the values from the view model, and then ad any other defaults (say for a `CreateDate` property) as required –  Aug 06 '18 at 07:33
  • @MichaelRandall This is a case of whatever is not false must be true. MS SQL server only uses the default value for not null columns. One must have a not null column and insert null values for SQL to employ the default value. Speculating, the C# POCO field then must be nullable because GetDate() is non-deterministic (changing return value for every call) and could not be a persisted computed value for example. – Zachary Scott Apr 27 '20 at 00:34

1 Answers1

1

This is just an answer to your question in a comment, and may not be the best solution

how does one make up values for DB ? Is it done by defining a constructor or a method on the model?

You can do it a number of ways, however this is a very simple solution

public class Track
{
    public Track()
    {
        LengthInMeters = 400;   
    }

    public int LengthInMeters { get; set; }        
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141