EF CORE数据注释和JOINS

时间:2018-01-13 12:49:45

标签: entity-framework-4 data-annotations entity-relationship

我试图查询旧数据库(我无法更改)。

每个表都有一个RecordId,它是一个唯一的id。这些表与其帐号字段相关联。

class tblOneToOne
{
[ForeignKey("Accountno")]
public string Accountno {get; set;}
public string Recordid {get; set; }
public string fields {get; set; }
}

class tblOneToMany
{
[ForeignKey("Accountno")]
public string Accountno {get; set;}
public string Recordid {get; set; }
public string Ref {get; set; }
}

class tblContact
{
[ForeignKey("Accountno")]
public string Accountno {get; set;}
[key]
public string Recordid {get; set; }
public string Company {get; set; }
public string Contact {get; set; }

public tblOneToOne tblOneToOne {get; set; }

public tblOneToMany tblOneToMany {get; set; }
}

我尝试使用Fluent Api指定外键

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<tblContact>().ToTable("Contact")
              .HasMany(c => c.tblOneToMany)
              .WithOne(cs => cs.tblContact)
              .HasForeignKey(c => c.Accountno);

}

然后我查询具有多个tblOneToMany记录的记录,但不返回任何结果。

var c = _context.tblContact
                .Include("tblOneToMany")
                .FirstOrDefaultAsync(c => c.Accountno == accountno);

  return c;

为了获得正确的结果,我应该做些什么?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

我终于设法使用Fluent API解决了我的问题。

我从类中删除了Foreignkey数据注释,并使用以下Fluent Api在表上指定ForeignKeys。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
  modelBuilder.Entity<tblContact>(entity =>
  {
    entity.HasKey(c => c.Accountno);

    entity.HasOne(c => c.tblOneToOne)
          .WithOne(c => c.tblContact)
          .HasForeignKey<tblOneToOne>(c => c.Accountno);

    entity.HasMany(c => c.tblOneToMany)
          .WithOne(c => c.tblContact)
          .HasForeignKey(cs => cs.Accountno);

  });
}