I have two tables in my database, BUNTS , which contains information about pieces of steel
CREATE TABLE BUNTS ( BUNTCODE INTEGER NOT NULL, BUNTNAME VARCHAR(20), BUNTSTEEL INTEGER, ...... );
and POLL_WEIGHT_BUNTS , which contains information about the operations that were performed on each bunt
CREATE TABLE POLL_WEIGHT_BUNTS ( PWBCODE INTEGER NOT NULL, PWBBUNTCODE INTEGER, PWBDEPARTMENTFROM INTEGER, PWBDEPARTMENTTO INTEGER .... );
One-to-many relationship. I matched these tables with models. Everything worked perfectly. Recently, I decided to add a field to the BUNTS table, which will refer to the last operation performed on bunt:
BUNTLASTOPER INTEGER
Now my models look like this:
[Table("BUNTS")] public class Bunt { [Key] [Column("BUNTCODE")] public int? Code { set; get; } [Column("BUNTNAME")] public string Name { set; get; } [Column("BUNTSTEEL")] public int? SteelCode { set; get; } [Column("BUNTLASTOPER")] public int? LastOperationID { set; get; } [ForeignKey("LastOperationID")] public BuntOperation LastOperation { set; get; } public virtual ICollection<BuntOperation> Operations { set; get; } } [Table("POLL_WEIGHT_BUNTS")] public class BuntOperation { [Key] [Column("PWBCODE")] public int? Code { set; get; } [Column("PWBBUNTCODE")] public int? BuntCode { set; get; } [ForeignKey("BuntCode")] public Bunt Bunt { set; get; } [Column("PWBDEPARTMENTFROM")] public int? DepartmentFromCode { set; get; } ..... }
After I did this, when I try to perform operations like this
return _context.Operations;
it generates an SQL statement with a new invalid Bunt_Code field
SELECT "B"."PWBCODE" AS "PWBCODE", "B"."PWBBUNTCODE" AS "PWBBUNTCODE", "B"."PWBDEPARTMENTFROM" AS "PWBDEPARTMENTFROM", .... "B"."Bunt_Code" AS "Bunt_Code" FROM "POLL_WEIGHT_BUNTS" AS "B"
I assume that now EF is looking for a field that is a foreign key for the BUNTS table and cannot find it. Therefore, it generates a Bunt_Code field that is not in my database. But I already have a Bunt property in the BuntOperation class that references the BUNTS table. What am I missing?
UPDATE looks like this solves my problem
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Bunt>().HasOptional(b => b.LastOperation).WithMany(); modelBuilder.Entity<Bunt>().HasMany(b => b.Operations).WithRequired(op => op.Bunt); }