I created a database in my ASP.NET Web API project, but inserting data causes a problem, because all columns by default are ColName (type, not null)
. I have StartDate
and EndDate
. With first insert I would like EndDate
to be null. I didn’t find any data attributes to allow null.
As well changing data manually in my ApplicationDBContextModelSnaphot
to ‘has default value NULL’ doesn’t do anything neither. How to optionally allow columns to be null?
ConstractionSite.cs
:
public class ConstractionSite
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[MaxLength(50)]
[Required]
public string Name { get; set; } = string.Empty;
public virtual ConstractionStatus Status { get; set; }
[ForeignKey("Status")]
public int StatusId { get; set; }
public DateOnly StartDate { get; set; }
public DateOnly EndDate { get; set; }
}
ApplicationDbContextModelSnapshot.cs
:
modelBuilder.Entity("WervenProj.Models.ConstractionSite", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<DateOnly>("EndDate")
.HasColumnType("date").HasDefaultValue(null);
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("nvarchar(50)");
b.Property<DateOnly>("StartDate")
.HasColumnType("date");
b.Property<int>("StatusId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("StatusId");
b.ToTable("ConstractionSites", (string)null);
});
I also manually updated migration file to the property EndDate nullable: true
and I ran update-database
. Nothing works.
Migration.cs
:
migrationBuilder.CreateTable(
name: "ConstractionSites",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
StatusId = table.Column<int>(type: "int", nullable: false),
StartDate = table.Column<DateOnly>(type: "date", nullable: false),
EndDate = table.Column<DateOnly>(type: "date", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ConstractionSites", x => x.Id);
table.ForeignKey(
name: "FK_ConstractionSites_ConstractionStatuses_StatusId",
column: x => x.StatusId,
principalTable: "ConstractionStatuses",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
Any tips? Thank you.
Another question: ConstractionSiteModel
has a foreign key related to Status
model. When I add with API ‘create new site’ via swagger and add manually ID for StatusId
field, it generates new instance in the Status
table as well with empty columns, but new a ID
key and changes StatusId
in ConstractionSites
with new generated. Why? Is there other way to create foreign key relation?