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 operations that had been performed on each bunt
CREATE TABLE POLL_WEIGHT_BUNTS (
PWBCODE INTEGER NOT NULL,
PWBBUNTCODE INTEGER,
PWBDEPARTMENTFROM INTEGER,
PWBDEPARTMENTTO INTEGER
....
);
The relationship is one-to-many. I mapped those tables to models. Everything worked just fine. Recently I've decided to add a field to table BUNTS which would reference to the last operation that had been 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've made this, when I try to query Operations like this
return _context.Operations;
it generates an SQL-statement with new incorrect field Bunt_Code
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 looks for a field that is a foreign key for BUNTS
table, and cant find it. So it generates Bunt_Code
field, which is missing in my database. But I already have a property Bunt
in BuntOperation
class, which references to BUNTS
table. What am I missing?
UPDATE seems 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);
}
seems 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);
}
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.