实体框架代码首先不起作用

时间:2011-06-20 06:13:58

标签: entity-framework entity ef-code-first

我有一个这样的课程:

class ClassA
{
    public long classAID {get; set;}
    public string Description {get; set;}
    public IEnumerable<ClassB> ClassBs {get; set;}
}

class ClassB
{
    public long classBID {get; set;} 
    public string SomeOtherDescription {get; set;}

    public IEnumerable<ClassA> {get; set;}
}
class TestContext: DBContext
{
    public DbSet<ClassA> ClassAs {get; set;}
    public DbSet<ClassB> ClassBs {get; set;}
}

H使DB具有与类和属性相同的列名和表名。 我已根据需要完成了web.config配置。当我尝试使用上面的方法来检索数据时,我得到了错误

"System.Data.Edm.EdmEntityType: : EntityType 'ClassA' has no key defined. Define the key for this EntityType." 

"System.Data.Edm.EdmEntityType: : EntityType 'ClassB' has no key defined. Define the key for this EntityType."

我厌倦了多种方法,例如设置键属性,外键属性等,但没有任何效果。请让我知道我错过了什么。

我使用的是C#4,我已通过以下网址验证:
http://www.asp.net/mvc/tutorials/mvc-music-store-part-4

http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

1 个答案:

答案 0 :(得分:0)

使用此:

public class ClassA
{
    public long ClassAID {get; set;}
    public string Description {get; set;}
    public virtual ICollection<ClassB> ClassBs {get; set;}
}

public class ClassB
{
    public long ClassBID {get; set;} 
    public string SomeOtherDescription {get; set;}
    public virtual ICollection<ClassA> {get; set;}
}

public class TestContext: DBContext
{
    public DbSet<ClassA> ClassAs { get; set; }
    public DbSet<ClassB> ClassBs { get; set; }
}

如您所见,导航属性标记为virtual。它将允许延迟加载=导航属性将在您的代码第一次访问属性时单独加载。它并不总是以这种方式加载导航属性的最佳方式,因为它会导致数据库的额外往返。因为EF还提供了切换加载,您明确告诉EF加载导航属性:

var query = context.ClassAs.Include(c => ClassBs);
相关问题