I have two tables Cargo
and CargoMovement
as follows:
public class Cargo
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CargoID { get; set; }
public string description { get; set; }
public virtual CargoMovement CargoMovement { get; set; }
}
public class CargoMovement
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public DateTime TimeOfTransit { get; set; }
public int CargoID { get; set; }
public virtual Cargo Cargo { get; set; }
}
Every Cargo
could have ONE or Zero CargoMovement
. Every CargoMovement
WILL have exactly one Cargo
.
CargoID
in Cargo table is primary key. CargoID
column in CargoMovement
should be the foreign key.
But when I write the following fluent API, the opposite happens.
modelBuilder.Entity<PisMark3.Models.Cargo.Cargo>()
.HasOptional(c => c.CargoMovement)
.WithRequired(cg => cg.Cargo)
.WillCascadeOnDelete(false);
resulting migration:
CreateTable(
"dbo.CargoMovements",
c => new
{
ID = c.Int(nullable: false, identity: true),
TimeOfTransit = c.DateTime(nullable: false),
CargoID = c.Int(nullable: false),
})
.PrimaryKey(t => t.ID)
.ForeignKey("dbo.Cargoes", t => t.ID)
.Index(t => t.ID);
Which means that when I try to insert
insert into dbo."CargoMovements" ("TimeOfTransit","CargoID")
values(NOW(),44)//44 is existing CargoID in Cargo table
It gives me an error that there is no id 1 in dbo.Cargo
table. (1 being the identity value of CargoMovement
)
I am looking for Fluent API solution.
For Fluent Api you need to use a parameterless WithMany() call to set the foreignkey as you can see here : One-to-One Foreign Key Associations so the new code would be:
modelBuilder.Entity<PisMark3.Models.Cargo.CargoMovement>()
.HasRequired(cg => cg.Cargo)
.WithMany()
.HasForeignKey(cg => cg.CargoID);
For data anotations try adding :
[Required, ForeignKey("Cargo")]
Above CargoID like this :
public class CargoMovement
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
public DateTime TimeOfTransit { get; set; }
[Required, ForeignKey("Cargo")]
public int CargoID { get; set; }
public virtual Cargo Cargo { get; set; }
}