实体框架代码首先包含方法和缺少导航属性

时间:2013-11-26 01:11:37

标签: entity-framework code-first

我有以下(缩写)DbContext:

public class O19Context : BaseContext<O19Context>
{
    public DbSet<PRJ> O19Set { get; set; }
}

[Table("AUFK")]
public class AUFK
{
  [ForeignKey("PRJ_GUID")]
  public PRJ PRJ {get; set;}
  [Key]
  public Guid AUFK_GUID {get; set;}
}

[Table("PRJ")]
public class PRJ
{
  [Key]
  public Guid PRJ_GUID {get; set;}
  public IQueryable<AUFK> AUFKS {get; set;}
}

当我运行以下代码时:

var db = new O19Context();
var prj = db.O19Set.Include("AUFKS")
    .Single(o => o.PRJ_GUID ==
        new Guid("6FE5E97B-9970-4E24-B051-9A710C03A030"));

我收到无效的Include路径错误。 EntityType PRJ不声明名为AUFKS的导航属性。

我哪里错了? 帕梅拉

2 个答案:

答案 0 :(得分:2)

了解EF是否喜欢您的POCO的好方法是EF Power Tools“查看实体数据模型(只读)”。

http://www.infoq.com/news/2013/10/ef-power-tools-beta4

我对您的代码进行了两处更改,现在它创建了一个小图...

EF Power Tools diagram

[TestClass]
public class O19Tests
{
    [TestMethod]
    public void O19Test1()
    {
        var db = new O19Context();

        var prj = db.O19Set.Include("AUFKS")
            .FirstOrDefault(o => o.PRJ_GUID ==
                new Guid("6FE5E97B-9970-4E24-B051-9A710C03A030"));
    }
}

public class O19Context : DbContext//<O19Context>
{
    public DbSet<PRJ> O19Set { get; set; }
}

[Table("AUFK")]
public class AUFK
{
    //[ForeignKey("PRJ_GUID")] //remove this... 
    //there is no PRJ_GUID field IN THIS CLASS
    public PRJ PRJ { get; set; }
    [Key]
    public Guid AUFK_GUID { get; set; }
}

[Table("PRJ")]
public class PRJ
{
    [Key]
    public Guid PRJ_GUID { get; set; }
    public IList<AUFK> AUFKS { get; set; } //use IList
}

答案 1 :(得分:0)

导航属性必须实现ICollection<T> - 您将属性定义为IQueryable<T>,我认为不支持该属性