我的DataBase中有两个表,BUNTS,其中包含有关钢件的信息
CREATE TABLE BUNTS ( BUNTCODE INTEGER NOT NULL,BUNTNAME VARCHAR(20),BUNTSTEEL INTEGER,...... );
和POLL_WEIGHT_BUNTS,其中包含有关每个bunt上执行的操作的信息
CREATE TABLE POLL_WEIGHT_BUNTS ( PWBCODE INTEGER NOT NULL,PWBBUNTCODE INTEGER,PWBDEPARTMENTFROM INTEGER,PWBDEPARTMENTTO INTEGER .... );
这种关系是一对多的.我将这些表映射到模型.一切都很好.
最近我决定在表BUNTS中添加一个字段,该字段将引用在bunt上执行的最后一个操作:
BUNTLASTOPER INTEGER
现在我的模型看起来像这样:
[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; } ..... }
在我做完之后,当我尝试查询这样的操作时
return _context.Operations;
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"
我假设现在EF查找的字段是BUNTS表的外键,并且无法找到它.所以它会生成Bunt_Code字段,这在我的数据库中是丢失的.但是我已经在BuntOperation类中有一个属性Bunt,它引用了BUNTS表.我错过了什么?
UPDATE
好像这解决了我的问题
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); }