c# – Entity Framework建议无效的字段名称

前端之家收集整理的这篇文章主要介绍了c# – Entity Framework建议无效的字段名称前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的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;

生成一个带有新的错误字段Bunt_Code的sql语句

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);
}

解决方法

好像这解决了我的问题
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);
}

猜你在找的C#相关文章