Reputation: 305
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 ?
Upvotes: 2
Views: 1130
Reputation: 81493
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; }
}
Upvotes: 1