I have created two classes: Máquina(Machine) and TipoMáquina(Type of Machine), and also, I tried to give to the class Máquina a foreign Key from Tipo Máquina (Note: if was the first migration. There were no other tables):
namespace Plataforma.Models
{
public class Máquina
{
[Key, Required]
public int MáquinaId { get; set; }
public int TipoMáquinaId { get; set; }
public virtual TipoMáquina TipoMáquina { get; set; }
}
}
namespace Plataforma.Models
{
public class TipoMáquina
{
[Key, Required]
public int TipoMáquinaId { get; set; }
public string DescripciónTipoMáq { get; set; }
public int PesoKg { get; set; }
public int AltoMt { get; set; }
public int LargoMt { get; set; }
public int AnchoMt { get; set; }
public virtual ICollection<Máquina> Máquinas { get; set; }
}
}
They were also included in the DBContext:
public class Plataforma: DbContext
{
public DbSet<Máquina> Máquinas { get; set; }
public DbSet<TipoMáquina> TipoMáquinas { get; set; }
}
However, the result in the DataBase was only the first table. No sign of TipoMáquina or the foreing key in the Máquina table and I don't know why.
I suspect it has something to do with the migration, in the down() section:
public partial class PrimeraRelación : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Máquina",
c => new
{
MáquinaId = c.Int(nullable: false, identity: true),
TipoMáquinaId = c.Int(nullable: false),
})
.PrimaryKey(t => t.MáquinaId)
.ForeignKey("dbo.TipoMáquina", t => t.TipoMáquinaId, cascadeDelete: true)
.Index(t => t.TipoMáquinaId);
CreateTable(
"dbo.TipoMáquina",
c => new
{
TipoMáquinaId = c.Int(nullable: false, identity: true),
})
.PrimaryKey(t => t.TipoMáquinaId);
}
public override void Down()
{
DropForeignKey("dbo.Máquina", "TipoMáquinaId", "dbo.TipoMáquina");
DropIndex("dbo.Máquina", new[] { "TipoMáquinaId" });
DropTable("dbo.TipoMáquina");
DropTable("dbo.Máquina");
}
}
}
Any suggestion is greatly appreciated.
Try the following modifications in TipoMachinas:
private ICollection<Máquina> máquinas;
public virtual ICollection<Máquina> Máquinas
{
get
{
return this.máquinas;
}
set
{
this.máquinas = value;
}
}
and in the constructor:
public TipoMáquina()
{
this.máquinas = new HashSet<Máquina>();
}
also imho it will be better if you name your primary key Id's only Id instead of ModelId :)
and finally you can add virtual to dbcontext's dbsets
public class Plataforma: DbContext
{
public virtual IDbSet<Máquina> Máquinas { get; set; }
public virtual IDbSet<TipoMáquina> TipoMáquinas { get; set; }
}
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.